Overview
Total the revenue of each product category across orders, items and products, without counting an order once per item.
- Chaining JOINs
- Summing at the right level
- Filtering on a joined table
Short Course
Chain joins to follow keys from table to table. Trap: after joining the
items, each order appears once per item, so summing the order's total counts
it several times. Sum the item amounts (qty * unit_price) instead.
SELECT p.category, SUM(i.qty) AS units_sold
FROM order_items AS i
JOIN products AS p ON p.id = i.product_id
JOIN orders AS o ON o.id = i.order_id
WHERE o.status = 'paid'
GROUP BY p.category;
Task
Return each product category with its revenue (qty * unit_price) from paid
orders, highest revenue first. In the database below, paid furniture sales
come to 120.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | nameTEXT | categoryTEXT |
|---|---|---|
| 1 | Pen | office |
| 2 | Desk | furniture |
| 3 | Chair | furniture |
| 4 | Ink | office |
| idINTEGER | statusTEXT | totalREAL |
|---|---|---|
| 10 | paid | 145.0 |
| 11 | refunded | 30.0 |
| 12 | paid | 12.0 |
| order_idINTEGER | product_idINTEGER | qtyINTEGER | unit_priceREAL |
|---|---|---|---|
| 10 | 2 | 1 | 120.0 |
| 10 | 1 | 5 | 2.0 |
| 10 | 4 | 3 | 5.0 |
| 11 | 3 | 1 | 30.0 |
| 12 | 1 | 6 | 2.0 |
Test Suites
Pending
Next
Output