Window functions
Top-N results per group
Choose the two highest-priced products in every category.
Lesson 64 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Choose the two highest-priced products in every category.
Run the example
sql
WITH Ranked AS (
SELECT ProductID, CategoryID, ListPrice,
ROW_NUMBER() OVER (PARTITION BY CategoryID
ORDER BY ListPrice DESC, ProductID) AS rn
FROM dbo.Products
)
SELECT CategoryID, ProductID, ListPrice, rn
FROM Ranked WHERE rn <= 2
ORDER BY CategoryID, rn;Read it step by step
- ROW_NUMBER partitions products by CategoryID and sorts each group by descending price.
- ProductID breaks price ties deterministically.
- The outer query keeps ranks 1 and 2 in each category, then orders the final result.
Check the result
| CategoryID | ProductID | ListPrice | rn |
|---|---|---|---|
| 1 | 2 | 129.00 | 1 |
| 1 | 3 | 79.00 | 2 |
| 2 | 6 | 45.00 | 1 |
| 2 | 5 | 12.00 | 2 |
| 3 | 9 | 119.00 | 1 |
| 3 | 7 | 89.00 | 2 |
| 4 | 11 | 65.00 | 1 |
| 4 | 10 | 28.00 | 2 |
| 5 | 13 | 189.00 | 1 |
| 5 | 15 | 149.00 | 2 |
Categories with fewer than two products contribute fewer than two rows.
Practice
Show the two highest-paid employees per DepartmentID, breaking salary ties by EmployeeID.
Check your answer and expected result
Reveal answer
sql
WITH Ranked AS (
SELECT EmployeeID, DepartmentID, AnnualSalary,
ROW_NUMBER() OVER (PARTITION BY DepartmentID
ORDER BY AnnualSalary DESC, EmployeeID) AS rn
FROM dbo.Employees
)
SELECT DepartmentID, EmployeeID, AnnualSalary, rn
FROM Ranked WHERE rn <= 2
ORDER BY DepartmentID, rn;| DepartmentID | EmployeeID | AnnualSalary | rn |
|---|---|---|---|
| 1 | 1 | 62000.00 | 1 |
| 1 | 3 | 42000.00 | 2 |
| 2 | 5 | 64000.00 | 1 |
| 2 | 6 | 41000.00 | 2 |
| 3 | 9 | 66000.00 | 1 |
| 3 | 10 | 43000.00 | 2 |
| 4 | 8 | 52000.00 | 1 |
| 4 | 12 | 50000.00 | 2 |
Each department contributes its two highest ranked employees when it has at least two.
Your progress
Reveal the check answer or reach the end to complete this lesson.