683

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.

How do I do this in SQL? (Preferably Oracle.)

I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.

9
  • 26
    What if there are multiple rows having the maximum date value for a particular userid? Commented Sep 23, 2008 at 18:29
  • What are the key fields of the table? Commented Jun 20, 2013 at 9:53
  • some solutions below compared: sqlfiddle.com/#!4/6d4e81/1 Commented Aug 7, 2014 at 7:27
  • 1
    @DavidAldridge, That column is likely unique. Commented Feb 3, 2015 at 3:38
  • stackoverflow.com/questions/2854257/… Commented Oct 11, 2015 at 10:29

36 Answers 36

1
2
-1
select UserId,max(Date) over (partition by UserId) value from users; 
Sign up to request clarification or add additional context in comments.

1 Comment

This will return all rows, not just one row per user.
-1

check this link if your questions seems similar to that page then i would suggest you the following query which will give the solution for that link

select distinct sno,item_name,max(start_date) over(partition by sno),max(end_date) over(partition by sno),max(creation_date) over(partition by sno), max(last_modified_date) over(partition by sno) from uniq_select_records order by sno,item_name asc;

will given accurate results related to that link

Comments

-1

Use the code:

select T.UserId,T.dt from (select UserId,max(dt) over (partition by UserId) as dt from t_users)T where T.dt=dt; 

This will retrieve the results, irrespective of duplicate values for UserId. If your UserId is unique, well it becomes more simple:

select UserId,max(dt) from t_users group by UserId; 

Comments

-1
SELECT a.userid,a.values1,b.mm FROM table_name a,(SELECT userid,Max(date1)AS mm FROM table_name GROUP BY userid) b WHERE a.userid=b.userid AND a.DATE1=b.mm; 

1 Comment

While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
-1

Below query can work :

SELECT user_id, value, date , row_number() OVER (PARTITION BY user_id ORDER BY date desc) AS rn FROM table_name WHERE rn= 1 

Comments

-2
SELECT a.* FROM user a INNER JOIN (SELECT userid,Max(date) AS date12 FROM user1 GROUP BY userid) b ON a.date=b.date12 AND a.userid=b.userid ORDER BY a.userid; 

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.