Given this data in table test
,
ID | val | date |
---|---|---|
1 | 111 | 2022-01-01 |
1 | 99 | 2020-01-01 |
1 | 95 | 2021-01-01 |
2 | 32 | 1990-07-25 |
2 | 8 | 1991-12-25 |
3 | 100 | 2022-05-28 |
4 | 0 | 2022-05-28 |
I would like to retrieve the record with the most recent date for each ID:
ID | val | date |
---|---|---|
1 | 111 | 2022-01-01 |
2 | 8 | 1991-12-25 |
3 | 100 | 2022-05-28 |
4 | 0 | 2022-05-28 |
This query provides the desired result, but is it possible to do this without using a derived table?
In our actual schema, the inner query may be expensive, as date
is not indexed.
select *
from test, (select id, max(date) as maxdate from test group by id) test2
where test.id = test2.id and test.date = test2.maxdate