SQL · Level 2 Joins

SQL Joins Across Three Tables

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

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;

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.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

products 4 rows
idINTEGERnameTEXTcategoryTEXT
1Penoffice
2Deskfurniture
3Chairfurniture
4Inkoffice
orders 3 rows
idINTEGERstatusTEXTtotalREAL
10paid145.0
11refunded30.0
12paid12.0
order_items 5 rows
order_idINTEGERproduct_idINTEGERqtyINTEGERunit_priceREAL
1021120.0
10152.0
10435.0
113130.0
12162.0
solution.sql
Test Suites Pending
Output