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.
Author |
Topic |
scabral7
Yak Posting Veteran
57 Posts |
Posted - 2009-08-11 : 12:58:53
|
Hi,i have a table similar to following:MR# Sequence123 1123 2123 3456 1456 2456 3456 4456 5456 6456 7456 8789 1789 2789 3789 4789 5789 6i want to get back up to only the first 5 sequence numbers for each MR# as follows:MR# Sequence123 1123 2123 3456 1456 2456 3456 4456 5789 1789 2789 3789 4789 5i am having some difficulty doing this. Does anyone have any good ideas on how to extract this data?thanksScott |
|
X002548
Not Just a Number
15586 Posts |
|
scabral7
Yak Posting Veteran
57 Posts |
Posted - 2009-08-11 : 13:07:18
|
But top 5 will give me just the top 5 rows of the table, i want the top 5 rows for each MR# field, so for each MR#, i want only the top 5 rows (or less if there are less than 5 rows). |
|
|
X002548
Not Just a Number
15586 Posts |
|
scabral7
Yak Posting Veteran
57 Posts |
Posted - 2009-08-11 : 15:15:07
|
sorry,i thought that would work, but the sequence numbers are not always in order.For example they could be like this:MR# Sequence123 12123 50123 65i basically need to get top 5 rows for each MR# group. Not sure if that explains it better... |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2009-08-11 : 16:05:49
|
Try this...Replace <urtable> with your actual table name.select * from (select *, ( select count(*) from <urtable> t1 where t1.MR# = t.MR# and t1.Sequence <= t.Sequence) as RowNumberfrom <urtable> t) t2where t2.RowNumber <= 5 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-08-14 : 02:01:15
|
see this linkhttp://sqlblogcasts.com/blogs/madhivanan/archive/2008/09/12/return-top-n-rows.aspx |
|
|
|
|
|