Unit 9 · JOIN, SUM
Joining tables and adding up values
Top 5 products by revenue
A JOIN lines up rows from two tables where a key matches, such as order_items.order_id = orders.id. Once joined, you can filter on columns from either table and aggregate across them.
SELECT o.id, SUM(oi.qty * oi.unit_price) AS order_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;Your task
Which five products brought in the most revenue? Count only delivered orders, since cancelled and returned orders did not earn anything.
You build it in 3 checked steps, one clause at a time.
This example adds up revenue per order. Your task adds it up per product, so think about what you GROUP BY.
Tables you will use: orders, order_items, products
Try it in your browserFree, no sign-up. Your query is checked as you go.