Lessons › SQL › Chapter 3: Summarising
SQL lesson
GROUP BY
GROUP BY splits your rows into groups based on a shared value, then runs a calculation.
Try this lesson free →Example
Summarising Retail Orders with GROUP BY
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
- Run the query without SUM so you can see what the unfiltered values look like.
SELECT category, revenue FROM orders GROUP BY category; - SUM totals the numbers in a column. Works on numeric columns only.
SELECT category, SUM(revenue) FROM orders GROUP BY category; - AS gives the SUM result a friendly column name so the output reads cleanly.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category;
Practice
1. Using orders, write a query to find the total revenue for each category.
SELECT category, SUM(revenue) FROM orders GROUP BY category2. Using store_sales, write a query to find the total revenue for each sale_id.
SELECT sale_id, SUM(revenue) FROM store_sales GROUP BY sale_id3. Using products, write a query to find the total price for each product_id.
SELECT product_id, SUM(price) FROM products GROUP BY product_id4. Using reviews, write a query to find the total rating for each customer_id.
SELECT customer_id, SUM(rating) FROM reviews GROUP BY customer_id5. Using employees, write a query to find the total salary for each employee_id.
SELECT employee_id, SUM(salary) FROM employees GROUP BY employee_idLearn 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 →