I am trying to write a query which will return only the rows, which time has the greatest value for each id
Table: positions
id time otherCols...
---------- ----------- ----------
1 1
1 2
3 1
1 3
2 1
3 2
Result should look like:
id time otherCols...
---------- ----------- ----------
1 3
2 1
3 2
I tried grouping by id but I don't know how to sort after that and pick only the top result.
You can use window functions:
An alternative method is a correlated subquery:
This is different from the first query in two respects:
id
, then this returns all rows for anid
. You can get that behavior usingrank()
in the first query.NULL
id
values orid
s where thetime
is uniformlyNULL
. The first query does.