Home > Database > Mysql Tutorial > How to Retrieve the Top 10 Records per Category Using SQL Server 2005?

How to Retrieve the Top 10 Records per Category Using SQL Server 2005?

Barbara Streisand
Release: 2025-01-21 06:06:08
Original
978 people have browsed it

How to Retrieve the Top 10 Records per Category Using 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 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
Copy after login

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!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template