Skip to content
Advertisement

ORACLE SQL find row with max date for each grouping

I am trying to write a query which will return only the rows, which time has the greatest value for each id

Result should look like:

I tried grouping by id but I don’t know how to sort after that and pick only the top result.

Advertisement

Answer

You can use window functions:

An alternative method is a correlated subquery:

This is different from the first query in two respects:

  • If there are duplicate times for an id, then this returns all rows for an id. You can get that behavior using rank() in the first query.
  • This will not return NULL id values or ids where the time is uniformly NULL. The first query does.
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement