Select top 10 records for each category Select top 10 records for each category sql-server sql-server

Select top 10 records for each category


If you are using SQL 2005 you can do something like this...

SELECT rs.Field1,rs.Field2     FROM (        SELECT Field1,Field2, Rank()           over (Partition BY Section                ORDER BY RankCriteria DESC ) AS Rank        FROM table        ) rs WHERE Rank <= 10

If your RankCriteria has ties then you may return more than 10 rows and Matt's solution may be better for you.


In T-SQL, I would do:

WITH TOPTEN AS (    SELECT *, ROW_NUMBER()     over (        PARTITION BY [group_by_field]         order by [prioritise_field]    ) AS RowNo     FROM [table_name])SELECT * FROM TOPTEN WHERE RowNo <= 10


SELECT r.*FROM(    SELECT        r.*,        ROW_NUMBER() OVER(PARTITION BY r.[SectionID]                          ORDER BY r.[DateEntered] DESC) rn    FROM [Records] r) rWHERE r.rn <= 10ORDER BY r.[DateEntered] DESC