views:

24

answers:

1

I'm trying to create a query that will pull the first 10 records of each id in a table.

Something like this sounds:

select distinct top 2 id, column1 from table group by id, column1


ID        Column1
1         ab
1         ac
1         ad
2         df
2         gf
2         dfdf
2         hgf
3         wa
3         hgh
3         dfgg
4         fgfgg

So the above table would return the first two results for each ID like this:

ID        Column1
1         ab
1         ac
2         df
2         gf
3         wa
3         hgh
4         fgfgg
+2  A: 

ROW_NUMBER() is very useful for this type of thing.

http://msdn.microsoft.com/en-us/library/ms186734.aspx

SELECT * FROM (
SELECT 
    ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) as RowNum, 
    ID, 
    Column1
FROM
    Table
) MyData
WHERE RowNum < 10
Ian Jacobs
ROW_NUMBER is what you're looking for.
ScottE
Sorry... Edited
Ian Jacobs
Yep! Thanks, worked just like I needed. I had a slight mix up on my end but figured it out with a little research and the link provided.
Mikecancook

related questions