Getting the N most recent rows over multiple groups
suggest changeGiven this data
User_ID | Completion_Date |
—— | —— |
1 | 2016-07-20 |
1 | 2016-07-21 |
2 | 2016-07-20 |
2 | 2016-07-21 |
2 | 2016-07-22 |
The leading semicolon and WITH without RECURSIVE are SQL Server style. Replace n with a literal, such as 1.
WITH CTE AS
(SELECT *,
ROW_NUMBER() OVER (PARTITION BY User_ID
ORDER BY Completion_Date DESC) Row_Num
FROM Data)
SELECT * FROM CTE WHERE Row_Num <= 1
With that limit, you get the one most recent row per User_ID:
User_ID | Completion_Date |Row_Num |
—— | —— |—— |
1 | 2016-07-21 |1
2 | 2016-07-22 |1
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents