Lessons › SQL › Chapter 3: Summarising
SQL lesson
GROUP BY
GROUP BY puts rows with the same value together, like every Electronics order. Then SUM or COUNT works out a number for each group. Put the grouping column in SELECT too, so you can see which total belongs to which group.
Try this lesson free →Example
One total per group
SELECT category, SUM(revenue) AS total_revenue
FROM orders
GROUP BY category| category | total_revenue |
|---|---|
| Electronics | 448.99 |
| Clothing | 108.25 |
| Home | 89.95 |
Step by step
- Puts rows with the same category together.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category - The SUM is worked out for each group, not the whole table.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category - Put the GROUP BY column in SELECT too, to see which total is which.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category
Practice
1. Using orders, find the total revenue for each category.
SELECT category, SUM(revenue) FROM orders GROUP BY category2. Using store_sales, find the total revenue for each store_id.
SELECT store_id, SUM(revenue) FROM store_sales GROUP BY store_id3. Using products, count how many products are in each category.
SELECT category, COUNT(*) FROM products GROUP BY category4. Using reviews, find the average rating for each product_id.
SELECT product_id, AVG(rating) FROM reviews GROUP BY product_id5. Using employees, find the total salary for each department.
SELECT department, SUM(salary) FROM employees GROUP BY departmentLearn 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 →