Aggregation
Conditional aggregation
Count several order statuses in one query over the same rows.
Lesson 29 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. Count several order statuses in one query over the same rows.
Run the example
sql
SELECT COUNT(*) AS TotalOrders,
SUM(CASE WHEN OrderStatus = N'Completed' THEN 1 ELSE 0 END) AS CompletedOrders,
SUM(CASE WHEN OrderStatus = N'Cancelled' THEN 1 ELSE 0 END) AS CancelledOrders
FROM dbo.Orders;Read it step by step
- COUNT(*) counts every order.
- Each CASE returns 1 for its chosen status and 0 otherwise.
- SUM adds those indicators, producing two counts over the same 5,000 rows.
Check the result
| TotalOrders | CompletedOrders | CancelledOrders |
|---|---|---|
| 5000 | 1250 | 1250 |
CompletedOrders and CancelledOrders are separate subsets; they do not cover every status.
Practice
Count Online orders and Online orders with Completed status in one result row.
Check your answer and expected result
Reveal answer
sql
SELECT COUNT(*) AS OnlineOrders,
SUM(CASE WHEN OrderStatus = N'Completed' THEN 1 ELSE 0 END) AS CompletedOnlineOrders
FROM dbo.Orders
WHERE OrderChannel = N'Online';| OnlineOrders | CompletedOnlineOrders |
|---|---|
| 3334 | 834 |
The first count covers every Online order; the second is its Completed subset.
Your progress
Reveal the check answer or reach the end to complete this lesson.