Sub topic 10
Grouping and Aggregating Joined Data
Assume you know basic SELECT, FROM, WHERE, and ORDER BY syntax, and understand primary keys and foreign keys. This chapter uses the customers and orders tables from earlier examples.
An inner join creates rows first. Aggregate functions then calculate values from those joined rows. GROUP BY divides the rows into groups, usually one group per customer, product, or other business entity.
Aggregate each customer's orders
This query counts orders and adds their totals for each customer:
SELECT
c.id,
c.name,
COUNT(o.id) AS order_count,
SUM(o.total) AS revenue
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;The join removes Chloe because she has no matching order. The result contains one row for Ada and one row for Ben.
| Customer | Order count | Revenue |
|---|---|---|
| Ada | 2 | 125.00 |
| Ben | 1 | 20.00 |
Include every non-aggregated selected column in GROUP BY. Grouping by the primary key and the displayed name is clear and works across common database systems.
Common aggregate functions include:
| Function | Purpose |
|---|---|
| `COUNT(column)` | Counts non-`NULL` values |
| `COUNT(*)` | Counts joined rows |
| `SUM(column)` | Adds values |
| `AVG(column)` | Calculates an average |
| `MIN(column)` | Finds the smallest value |
| `MAX(column)` | Finds the largest value |
Watch for row multiplication
A join can repeat a row from one table. Suppose one order has several order items. Joining orders to order_items produces one row for each item. The order total appears on every one of those rows.
-- Incorrect when an order has multiple items.
SELECT SUM(o.total) AS revenue
FROM orders AS o
INNER JOIN order_items AS i
ON i.order_id = o.id;This query counts the same order total once per item. It overstates revenue.
Aggregate the order table before joining it to another one-to-many table, or calculate order-level totals in a separate query:
SELECT SUM(o.total) AS revenue
FROM orders AS o;If you need item information and order-level revenue together, pre-aggregate items by order:
SELECT
o.id AS order_id,
o.total,
item_totals.item_quantity
FROM orders AS o
INNER JOIN (
SELECT order_id, SUM(quantity) AS item_quantity
FROM order_items
GROUP BY order_id
) AS item_totals
ON item_totals.order_id = o.id;The subquery produces one row per order, so the later join does not multiply each order by its number of items.
Exercise
Why can SUM(o.total) be wrong after joining orders to order_items, and what is one way to prevent the error?
Show answer
Each order total can repeat once per order item. Aggregate order totals before the one-to-many join, or calculate the order-level sum separately.