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.
I don't know your exact columns names, but it would be something like this:
Wouldn't a QUALIFY clause be both simplest and best?
For context, on Teradata here a decent size test of this runs in 17s with this QUALIFY version and in 23s with the 'inline view'/Aldridge solution #1.
With PostgreSQL 8.4 or later, you can use this:
Not being at work, I don't have Oracle to hand, but I seem to recall that Oracle allows multiple columns to be matched in an IN clause, which should at least avoid the options that use a correlated subquery, which is seldom a good idea.
Something like this, perhaps (can't remember if the column list should be parenthesised or not):
EDIT: Just tried it for real:
So it works, although some of the new-fangly stuff mentioned elsewhere may be more performant.
First try I misread the question, following the top answer, here is a complete example with correct results:
--
--