Extracting Top 10 Records per Category in SQL Server 2005
This guide demonstrates how to efficiently retrieve the top 10 records for each category using a single SQL Server 2005 query.
Here's the solution:
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
This query employs the RANK()
function to assign a rank to each record within its category, based on the RankCriteria
(the column defining the ranking order). The PARTITION BY Section
clause ensures independent ranking within each category. RANK()
assigns sequential ranks, starting at 1 for the highest-ranked record.
The WHERE Rank <= 10
clause filters the results, limiting the output to the top 10 records in each category. It's crucial to remember that if ties exist in RankCriteria
, more than 10 records might be returned for a category.
The above is the detailed content of How to Retrieve the Top 10 Records per Category Using SQL Server 2005?. For more information, please follow other related articles on the PHP Chinese website!