Aggregation
GROUP BY
Count customers within each region.
Lesson 27 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 customers within each region.
Run the example
sql
SELECT Region, COUNT(*) AS CustomerCount
FROM dbo.Customers
GROUP BY Region
ORDER BY Region;Read it step by step
- GROUP BY Region forms one group for each distinct Region value.
- COUNT(*) counts customer rows in each group.
- ORDER BY Region sorts the summary rows; grouping alone promises no output order.
Check the result
| Region | CustomerCount |
|---|---|
| Midlands | 5 |
| North | 6 |
| South | 7 |
| West | 2 |
The counts add up to all 20 customers.
Practice
Count customers in each City and display cities alphabetically.
Check your answer and expected result
Reveal answer
sql
SELECT City, COUNT(*) AS CustomerCount
FROM dbo.Customers
GROUP BY City
ORDER BY City;| City | CustomerCount |
|---|---|
| Birmingham | 3 |
| Bristol | 2 |
| Cardiff | 2 |
| Leeds | 2 |
| Leicester | 2 |
| London | 5 |
| Manchester | 2 |
| York | 2 |
The city counts add up to 20 customers.
Your progress
Reveal the check answer or reach the end to complete this lesson.