Home >Database >Mysql Tutorial >How to Retrieve the Top 10 Records from Each Category Using SQL?
Extracting Top 10 Records Per Category with SQL
A frequent database operation involves retrieving the top entries from each category in a single SQL query. This is typically accomplished using ranking functions combined with partitioning. Let's examine how to do this using SQL, focusing on a database with categories like "business," "local," and "feature."
SQL Server 2005 Solution for Top 10 Records Per Section
In SQL Server 2005, the following query provides the desired outcome:
<code class="language-sql">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</code>
This query leverages the RANK()
function to rank each record within its respective section, based on the RankCriteria
column. The PARTITION BY
clause separates records by Section
, ensuring independent ranking for each category.
Handling Ties in Rankings
It's crucial to understand that RANK()
doesn't handle ties effectively. If multiple records share the same RankCriteria
value, they receive the same rank. This can lead to more than 10 records returned for a section if ties exist.
To mitigate this, consider using ROW_NUMBER()
instead. ROW_NUMBER()
assigns unique sequential numbers within each partition, providing a more precise top 10 selection, although this approach might add complexity in some scenarios.
The above is the detailed content of How to Retrieve the Top 10 Records from Each Category Using SQL?. For more information, please follow other related articles on the PHP Chinese website!