Advanced T-SQL and application patterns
End-to-end SQL Server capstone
Combine filtering, joins, aggregation, and ranking for a repeatable customer-spend report.
Lesson 84 of 84
Reading: about 3 min
Lesson + practice: about 20 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Combine filtering, joins, aggregation, and ranking for a repeatable customer-spend report.
Run the example
WITH CustomerSpend AS (
SELECT o.CustomerID, SUM(i.Quantity * i.UnitPrice) AS Spend
FROM dbo.Orders AS o
JOIN dbo.OrderItems AS i ON i.OrderID = o.OrderID
WHERE o.OrderStatus IN (N'Shipped', N'Completed')
GROUP BY o.CustomerID
), Ranked AS (
SELECT CustomerID, Spend,
ROW_NUMBER() OVER (ORDER BY Spend DESC, CustomerID) AS rn
FROM CustomerSpend
)
SELECT r.CustomerID, c.FirstName, r.Spend, r.rn
FROM Ranked AS r JOIN dbo.Customers AS c ON c.CustomerID = r.CustomerID
WHERE r.rn <= 3 ORDER BY r.rn;Read it step by step
- Filter to Shipped and Completed orders before summing their order-item line totals.
- GROUP BY CustomerID establishes one spend row per customer, preventing join-count inflation.
- ROW_NUMBER ranks spend with CustomerID as a deterministic tie-breaker; the final join adds the name. ROW_NUMBER is safe here because the three highest spend values are all different; when ties are possible, use RANK, as the practice does.
Check the result
| CustomerID | FirstName | Spend | rn |
|---|---|---|---|
| 8 | Nina | 134722.00 | 1 |
| 12 | Mila | 96695.00 | 2 |
| 4 | Isla | 92711.50 | 3 |
Spend is from qualifying order lines at their stored UnitPrice, not current product ListPrice.
Practice
Find products in the top three rank positions by sold quantity in Shipped or Completed orders. Include every product tied at a qualifying rank.
Check your answer and expected result
Reveal answer
WITH ProductUnits AS (
SELECT i.ProductID, SUM(i.Quantity) AS UnitsSold
FROM dbo.Orders AS o
JOIN dbo.OrderItems AS i ON i.OrderID = o.OrderID
WHERE o.OrderStatus IN (N'Shipped', N'Completed')
GROUP BY i.ProductID
), Ranked AS (
SELECT ProductID, UnitsSold,
RANK() OVER (ORDER BY UnitsSold DESC) AS SalesRank
FROM ProductUnits
)
SELECT ProductID, UnitsSold, SalesRank
FROM Ranked WHERE SalesRank <= 3
ORDER BY UnitsSold DESC, ProductID;| ProductID | UnitsSold | SalesRank |
|---|---|---|
| 9 | 669 | 1 |
| 1 | 668 | 2 |
| 5 | 668 | 2 |
| 8 | 668 | 2 |
| 12 | 668 | 2 |
RANK gives products with equal UnitsSold the same position. Product 9 ranks first at 669 units; Products 1, 5, 8, and 12 all rank second at 668 units, so the answer has five rows.
Your progress
Reveal the check answer or reach the end to complete this lesson.