Lessons › SQL › Chapter 3: Summarising
SQL lesson
GROUP BY with multiple columns
GROUP BY two columns makes a group for every mix of them, like Electronics in the North and Electronics in the South. List both columns in SELECT and in GROUP BY.
Try this lesson free →Example
Groups within groups
SELECT category, region, SUM(revenue) AS total_revenue
FROM orders
GROUP BY category, region
ORDER BY category, region| category | region | total_revenue |
|---|---|---|
| Clothing | North | 89.99 |
| Clothing | South | 134.75 |
| Electronics | North | 730.0 |
| Electronics | South | 215.5 |
Step by step
- A group for every mix of category and region.
SELECT category, region, SUM(revenue) AS total_revenue FROM orders GROUP BY category, region ORDER BY category, region - Electronics North and Electronics South become separate rows.
SELECT category, region, SUM(revenue) AS total_revenue FROM orders GROUP BY category, region ORDER BY category, region - List both grouping columns in SELECT too.
SELECT category, region, SUM(revenue) AS total_revenue FROM orders GROUP BY category, region ORDER BY category, region
Practice
1. Using orders, find the total revenue for each category and channel.
SELECT category, channel, SUM(revenue) FROM orders GROUP BY category, channel2. Using store_sales, count the sales for each store_id and channel.
SELECT store_id, channel, COUNT(*) FROM store_sales GROUP BY store_id, channel3. Using employees, count the employees in each department and role.
SELECT department, role, COUNT(*) FROM employees GROUP BY department, role4. Using shipments, count the shipments for each carrier and status.
SELECT carrier, status, COUNT(*) FROM shipments GROUP BY carrier, status5. Using inventory, find the total stock_count for each warehouse and category.
SELECT warehouse, category, SUM(stock_count) FROM inventory GROUP BY warehouse, categoryLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →