Lessons › SQL › Chapter 3: Summarising
SQL lesson
GROUP BY with multiple columns
GROUP BY with multiple columns splits results into finer slices by combining two or more grouping criteria at once, giving you a separate total for every unique combination.
Try this lesson free →Example
Breaking Down Retail Results with GROUP BY on Multiple Columns
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
- Run the query without SUM so you can see what the unfiltered values look like.
SELECT category, region, revenue FROM orders GROUP BY category, region ORDER BY category, region; - SUM totals the numbers in a column. Works on numeric columns only.
SELECT category, region, SUM(revenue) FROM orders GROUP BY category, region ORDER BY category, region; - AS gives the SUM result a friendly column name so the output reads cleanly.
SELECT category, region, SUM(revenue) AS total_revenue FROM orders GROUP BY category, region ORDER BY category, region;
Practice
1. Using orders, write a query to count rows for each combination of order_id and customer_id.
SELECT order_id, customer_id, COUNT(*) FROM orders GROUP BY order_id, customer_id2. Using store_sales, write a query to count rows for each combination of sale_id and store_id.
SELECT sale_id, store_id, COUNT(*) FROM store_sales GROUP BY sale_id, store_id3. Using products, write a query to count rows for each combination of product_id and brand.
SELECT product_id, brand, COUNT(*) FROM products GROUP BY product_id, brand4. Using reviews, write a query to count rows for each combination of review_id and product_id.
SELECT review_id, product_id, COUNT(*) FROM reviews GROUP BY review_id, product_id5. Using employees, write a query to count rows for each combination of employee_id and full_name.
SELECT employee_id, full_name, COUNT(*) FROM employees GROUP BY employee_id, full_nameLearn 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 →