Home › Learn › SQL › Aggregates

GROUP BY

Lesson 13 of 26. One row per group, with an aggregate for each.

GROUP BY category splits the rows into one bucket per category and runs the aggregates per bucket: SELECT category, COUNT(*) FROM products GROUP BY category; gives each category with its number of products. Every column in the select list must be either grouped or aggregated.

This is the shape of most reports: sales per month, orders per customer, employees per department. Group by several columns to get finer buckets, and add ORDER BY to sort the summary.

SELECT dept, AVG(salary) FROM employees GROUP BY dept;

Your task

Show each customer_id from orders with the number of orders as order_count and the total quantity across them as total_quantity.

Part of the final project. customer_orders is the view of how many orders each customer has placed, and how many items. It is saved in this browser and loaded into Project: the order report when you get there.

Hint 1

customer_id, COUNT(*) AS order_count, SUM(quantity) AS total_quantity

Show the solution
SELECT customer_id, COUNT(*) AS order_count, SUM(quantity) AS total_quantity
FROM orders
GROUP BY customer_id;

    Runs SQLite compiled to WebAssembly in this tab; the database is rebuilt before every run.