Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Get only one record per users.

Author  Topic 

ugh3012
Yak Posting Veteran

62 Posts

Posted - 2013-10-29 : 13:26:26
I need to create a query that will select only one record out of x number of record per user id.


Sample Data
User ID | Date |Status
001 |10/1/2013 |01
001 |10/2/2013 |A1
002 |1/1/2013 |BB
003 |5/8/2013 |EE
003 |4/2/2013 |BB

Expected Result
User ID | Date |Status
001 | 10/2/2013 |A1
002 | 1/1/2013 |BB
003 | 5/8/2013 |EE

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2013-10-29 : 13:42:30
Here's one way:

select [User ID]
, [Date]
, [Status]
from (
select [User ID]
, [Date]
, [Status]
, rn = row_number() over (partition by [user id] order by [date] desc)
from yourtable
) d
where rn = 1


Be One with the Optimizer
TG
Go to Top of Page

ushavellala
Starting Member

10 Posts

Posted - 2013-10-29 : 17:50:26
Select distinct UserID
from yourtable
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2013-10-30 : 05:33:31
quote:
Originally posted by ushavellala

Select distinct UserID
from yourtable


You need other columns as well. Try the code used by TG. Also read this for more such methods http://beyondrelational.com/modules/2/blogs/70/posts/10845/return-top-n-rows.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -