Joins with GROUP BY
Summaries that need data from several tables.
Joins and grouping work together. First the join builds combined rows, then GROUP BY makes groups and the aggregates summarize them. This is how you answer questions like "how much is each order worth?" when quantities live in order_items and prices live in products.
SELECT oi.order_id, SUM(oi.quantity * p.price) AS total
FROM order_items oi
JOIN products p ON oi.product_id = p.id
GROUP BY oi.order_id;Each item row gets its product's price, quantity * price is the line cost, and SUM adds the lines of each order.
Group by the id, and show the name. Grouping by name would merge two different customers who happen to share a name.