Home >Database >Mysql Tutorial >How to Retrieve the Top 10 Records for Each Category in SQL Server 2005?

How to Retrieve the Top 10 Records for Each Category in SQL Server 2005?

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 05:52:13349browse

How to Retrieve the Top 10 Records for Each Category in SQL Server 2005?

Extracting Top 10 Records per Category in SQL Server 2005

This guide demonstrates how to efficiently retrieve the top 10 records for each category (business, local, feature) from a SQL Server 2005 table, ordered by entry date and filtered by a date range.

SQL Approach:

This solution leverages a subquery and a window function. The subquery partitions the data by category (Section column) and ranks records within each partition based on a descending RankCriteria (e.g., date). The main query then selects only those records with a rank less than or equal to 10.

<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>

Important Notes:

  • Duplicate RankCriteria: If multiple records share the same RankCriteria value within a category, the RANK() function may return more than 10 records for that category.
  • Guaranteed Top 10: To guarantee exactly 10 records per category, ensure your RankCriteria column has unique values within each category. Consider using ROW_NUMBER() instead of RANK() if strict ordering is needed, even with ties. ROW_NUMBER() assigns a unique rank to each row, regardless of ties.

This optimized query provides a robust solution for retrieving top-N records per category in SQL Server 2005. Remember to replace table, Field1, Field2, and RankCriteria with your actual table and column names. Adding a WHERE clause to the inner query will allow you to filter by date range as needed.

The above is the detailed content of How to Retrieve the Top 10 Records for Each Category in SQL Server 2005?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn