Window functions
OVER and PARTITION BY
Calculate a per-customer count while retaining each order row.
Lesson 58 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. Calculate a per-customer count while retaining each order row.
Run the example
sql
SELECT TOP (5) OrderID, CustomerID,
COUNT(*) OVER (PARTITION BY CustomerID) AS CustomerOrderCount
FROM dbo.Orders
ORDER BY OrderID;Read it step by step
- PARTITION BY forms a window for each CustomerID.
- COUNT(*) OVER returns a count on every original order row rather than collapsing to one row per customer.
- The outer ORDER BY, not the partition, selects the five displayed orders.
Check the result
| OrderID | CustomerID | CustomerOrderCount |
|---|---|---|
| 1 | 1 | 250 |
| 2 | 2 | 250 |
| 3 | 3 | 250 |
| 4 | 4 | 250 |
| 5 | 5 | 250 |
The count covers all orders in the customer partition before TOP selects five output rows.
Practice
Show Products 1–5 with the count of products in each CategoryID partition.
Check your answer and expected result
Reveal answer
sql
SELECT TOP (5) ProductID, CategoryID,
COUNT(*) OVER (PARTITION BY CategoryID) AS CategoryProductCount
FROM dbo.Products
ORDER BY ProductID;| ProductID | CategoryID | CategoryProductCount |
|---|---|---|
| 1 | 1 | 3 |
| 2 | 1 | 3 |
| 3 | 1 | 3 |
| 4 | 2 | 3 |
| 5 | 2 | 3 |
Each row retains its ProductID and shows the size of its full category partition.
Your progress
Reveal the check answer or reach the end to complete this lesson.