How to Select the Row with Maximum Date
There is the following table. You need to select the row with the maximum date and other fields of that row.
id | usr | action | datetime
____________________________________
1 | Ivanov | created | datetime1
2 | Ivanov | changed | datetime2
3 | Petrov | changed | datetime3
4 | Petrov | changed | datetime4
5 | Petrov | changed | datetime5
6 | Sidorov | changed | datetime6
7 | Sidorov | Signed | datetime7
You need to get information about the latest actions. Who and when last created, changed and signed. That is, the output should be:
1 | Ivanov | created | datetime1
6 | Sidorov | changed | datetime6
7 | Sidorov | Signed | datetime7
Solution for PostgreSQL
select distinct on (1)
-- select only unique values by the first field (action) from the selection
action,
usr,
datetime
-- output action, usr, datetime
from table t1
order by 1, datetime desc
-- for the selection, sort by the first field (action), then by date in descending order
Published 30.11.2016
