Retrieve the Top N Rows for Each Category SQL Server

Retrieve the Top N Rows for Each Category Query Using MS SQL Server?


To retrieve the top N rows for each category in SQL Server, you can use window functions, specifically ROW_NUMBER(), which allows you to rank rows within each category. Then, you can filter based on this ranking.

Here’s a general approach assuming you have a table with categories and some criteria to rank the rows (e.g., sales, scores, etc.):

Example Table Structure

Assume you have a table:

  • Products:
    • ProductID
    • CategoryID
    • ProductName
    • SalesAmount

SQL Query to Retrieve the Top N Rows for Each Category

WITH RankedProducts AS (
    SELECT
        ProductID,
        CategoryID,
        ProductName,
        SalesAmount,
        ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY SalesAmount DESC) AS rn
    FROM Products
)
SELECT
    ProductID,
    CategoryID,
    ProductName,
    SalesAmount
FROM RankedProducts
WHERE rn <= @TopN
ORDER BY CategoryID, rn;

Explanation:

  1. CTE RankedProducts:

    • ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY SalesAmount DESC) AS rn: This assigns a unique sequential integer (rn) to each row within each CategoryID partition, ordered by SalesAmount in descending order. This means the highest sales amount gets 1, the next gets 2, and so on.
  2. Final Query:

    • WHERE rn <= @TopN: Filters the rows to include only those where the row number is less than or equal to @TopN, which is a parameter representing the top N rows you want to retrieve for each category.

Example Data and Results

Assume the Products table has the following data:

ProductIDCategoryIDProductNameSalesAmount
1AProduct 11000
2AProduct 21500
3AProduct 32000
4BProduct 43000
5BProduct 53500
6BProduct 62500
7CProduct 7500
8CProduct 8700

If you want to retrieve the top 2 products per category, setting @TopN to 2, the query will result in:

ProductIDCategoryIDProductNameSalesAmount
3AProduct 32000
2AProduct 21500
5BProduct 53500
4BProduct 43000
8CProduct 8700
7CProduct 7500

This result shows the top 2 products by sales amount for each category.

You can execute this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to retrieve the top N rows for each category. Adjust the @TopN parameter to the number of top rows you need.


Post a Comment

Previous Post Next Post