I’m trying to put sequence id which should start from current date then backwards and should only limit up until 5 rows. I can’t do by date as there are times there are missing date row so I still have to follow the current date to whatever date is next backwards
I already came up with a query but it seems that it doesn’t really start with current date backwards. Any other approach I can do?
SELECT *,
ROW_NUMBER() over (partition by employee_id order by date rows 5 preceding exclude current row)
from employee table
2
Answers
Try the following query:
Example with sample data:
Temp Table:
Sample data:
Query:
Result:
I think you also need to list employee columns such as employee id(you did
select *
). If so, you need something like this:Inside of the lateral join you get last 5 date for each group and then iterate it.
Fiddle
Also, there is a different version of it:
In order to compare them I increased the data volume and you can see comparison of explain output for both queries using fiddle.
In short, second query is faster.
Note: there were mistakes on the answer, they were fixed.