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
 Query help

Author  Topic 

jim_jim
Constraint Violating Yak Guru

306 Posts

Posted - 2011-01-11 : 19:30:48
Hi Guys
Need help writing a query to get only top3 claim numbers for members based on service date.


Sample Data

Memberid Claimno Service date
1 xyz 1/1/2010
1 xcz 1/3/2010
1 xcv 1/5/2010
1 xbn 1/7/2010
1 xmn 2/9/2010
2 zxc 4/1/2010
2 zvb 5/1/2010

trying to write a query so that just the top 3 claim numbers are retreived for all the members based on the service date


Memberid Claimno Service date
1 xmn 2/9/2010
1 xbn 1/7/2010
1 xcv 1/5/2010
2 zop 8/1/2010
2 zmk 7/1/2010
2 znm 6/1/2010









singularity
Posting Yak Master

153 Posts

Posted - 2011-01-11 : 19:44:43
[code]
select memberid, claimno, servicedate
from
(select memberid, claimno, servicedate,
row_number() over (partition by memberid order by servicedate desc) as rn
from yourtable) a
where rn <= 3
[/code]
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-01-12 : 02:16:19
Also refer
http://beyondrelational.com/blogs/madhivanan/archive/2008/09/12/return-top-n-rows.aspx

Madhivanan

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

- Advertisement -