I have a sales table, where it shows the information below
ID_sale | sales_person | sale_date |
---|---|---|
7 | 50 | 19/10/2022 |
6 | 43 | 17/9/2022 |
5 | 50 | 15/3/2022 |
4 | 43 | 13/2/2022 |
2 | 50 | 22/1/2022 |
3 | 10 | 05/2/2022 |
1 | 12 | 07/1/2022 |
and I want to create a query where I get the following information, basically the most recent date of the sale and the last sale date they made
ID_sale | sales_person | recent_sale | last_sale |
---|---|---|---|
7 | 50 | 19/10/2022 | 15/3/2022 |
6 | 43 | 17/9/2022 | 13/2/2022 |
3 | 10 | 05/2/2022 | 05/2/2022 |
1 | 12 | 07/1/2022 | 07/1/2022 |
Thank you
4
Answers
We use
rank()
to find the most recent couple of sales and then pivot the results.Fiddle
You could add a CTE first where you add a row_nmber to get the order of the dates and then select them
update
I added a solution without GROUP BY and further window functions at the end
fiddle
Use
ROW_NUMBER()
to filter most recent rows andLEAD()
forlast_sale
. UseCOALESCE()
for the case when nolast_sale
exists:For older versions that don’t support window function (like
ROW_NUMBER()
andLEAD()
) you can use correlated (bysales_person
) subqueries for last_sale and for the recent row filter in the WHERE clause:Not as efficient as a window function, but simpler and portable:
Unless you have 100’s of millions of sales, this will perform OK if you have an index on sales_person.