SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Get only one record per users.
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

ugh3012
Yak Posting Veteran

62 Posts

Posted - 10/29/2013 :  13:26:26  Show Profile  Reply with Quote
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


Edited by - ugh3012 on 10/29/2013 13:27:04

TG
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 10/29/2013 :  13:42:30  Show Profile  Reply with Quote
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

USA
10 Posts

Posted - 10/29/2013 :  17:50:26  Show Profile  Reply with Quote
Select distinct UserID
from yourtable
Go to Top of Page

madhivanan
Premature Yak Congratulator

India
22761 Posts

Posted - 10/30/2013 :  05:33:31  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.56 seconds. Powered By: Snitz Forums 2000