Table:
UserId, Value, Date.
I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle)
Update: Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.
Use
ROW_NUMBER()
to assign a unique ranking on descendingDate
for eachUserId
, then filter to the first row for eachUserId
(i.e.,ROW_NUMBER
= 1).IMHO this works. HTH
I'm quite late to the party but the following hack will outperform both correlated subqueries and any analytics function but has one restriction: values must convert to strings. So it works for dates, numbers and other strings. The code does not look good but the execution profile is great.
The reason why this code works so well is that it only needs to scan the table once. It does not require any indexes and most importantly it does not need to sort the table, which most analytics functions do. Indexes will help though if you need to filter the result for a single userid.
If (UserID, Date) is unique, i.e. no date appears twice for the same user then:
If you're using Postgres, you can use
array_agg
likeI'm not familiar with Oracle. This is what I came up with
Both queries return the same results as the accepted answer. See SQLFiddles:
Assuming Date is unique for a given UserID, here's some TSQL: