uid | created_date | user_id |
---|---|---|
1 | 2023-07-05 05:50:00.000 | 1 |
2 | 2023-07-05 06:50:00.000 | 1 |
3 | 2023-07-05 06:50:00.000 | 1 |
4 | 2023-07-05 06:40:46.000 | 2 |
5 | 2023-07-05 06:57:46.000 | 2 |
6 | 2023-07-05 06:43:46.000 | 2 |
For example, above is the data.
I am looking for output to have something like this
uid | created_date | user_id | reason |
---|---|---|---|
3 | 2023-07-05 06:50:00.000 | 1 | as date is same I chose latest uid |
5 | 2023-07-05 06:57:46.000 | 2 | choosing the latest date |
2
Answers
A
CTE
with a ROW_NUMBER
will do the trickThe rownumber will add a number to each row starting from 1 where for a group (
PARTIION BY
) .The
ORDER BY
is crutial to get the wanted result.fiddle
For few rows per group,
DISTINCT ON
is simplest and fastest:Best supported with a matching index on
tbl (user_id, created_date DESC, uid DESC)
. Depends on undisclosed data distribution and cardinalities.Detailed explanation (including faster alternatives for many rows per group):