Oracle: Find value for each UserID that has latest date

1137475 pts.
Tags:
Oracle
SQL
In my Oracle table, I have three different columns: UserID, Value and Date. I'm trying to get the value for each UserID (that has the latest date). How can I do that? Can I use SQL?
1

Answer Wiki

Thanks. We'll let you know when a new response is added.

There are different ways.

Here is one:

SELECT userid, value
FROM your_table t
WHERE date_column =
  (
    SELECT MAX(date_column)
    FROM your_table
    WHERE userid = t.userid
  );

And here is a more efficient one, which uses an analytic function and only requires one table scan:

WITH ordered AS
  (
    SELECT userid, value, ROW_NUMBER() OVER (partition BY userid order by
      date_column DESC) rn
    FROM your_table
  )
SELECT userid, value
FROM ordered
WHERE rn = 1;

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

Thanks! We'll email you when relevant content is added and updated.

Following

Share this item with your network: