Aggregation
Avoiding misleading aggregate results
Recognize how a one-to-many join can inflate an order count.
Lesson 31 of 84
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Intermediate
On this page4 sections
This lesson uses the unmodified DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Recognize how a one-to-many join can inflate an order count.
The example uses JOIN, which Chapter 6 teaches in full. For now, read JOIN dbo.OrderItems AS i ON i.OrderID = o.OrderID as: pair each order with every order-item row that has the same OrderID.
Run the example
SELECT COUNT(*) AS JoinedRows,
COUNT(DISTINCT o.OrderID) AS DistinctOrders
FROM dbo.Orders AS o
JOIN dbo.OrderItems AS i ON i.OrderID = o.OrderID
WHERE o.OrderID BETWEEN 1 AND 3;Read it step by step
- Each selected order has two OrderItems rows in dataset v1.0.0.
- The join therefore produces six rows for three orders.
- COUNT(DISTINCT o.OrderID) counts order identities rather than joined lines.
Check the result
| JoinedRows | DistinctOrders |
|---|---|
| 6 | 3 |
JoinedRows and DistinctOrders answer different questions; neither is inherently wrong.
Practice
Repeat the comparison for OrderID values 10 through 12.
Check your answer and expected result
Reveal answer
SELECT COUNT(*) AS JoinedRows,
COUNT(DISTINCT o.OrderID) AS DistinctOrders
FROM dbo.Orders AS o
JOIN dbo.OrderItems AS i ON i.OrderID = o.OrderID
WHERE o.OrderID BETWEEN 10 AND 12;| JoinedRows | DistinctOrders |
|---|---|
| 6 | 3 |
Each of the three orders has two lines, so the join returns six rows but three distinct orders.
Your progress
Reveal the check answer or reach the end to complete this lesson.