Revenue doubled after adding a join
A daily revenue query joined orders to payments. Someone added a join to shipments to show the shipped count as well, and revenue for some days doubled or tripled. Each order can have several payments and several shipments. Why, and how should the query be written?
Think it through or sketch an answer first, then open the hint or the solution.
Show a hint
Count how many rows one order becomes after joining two one-to-many tables.
Show the solution
Joining two one-to-many children to the same parent multiplies rows: an order with 2 payments and 3 shipments becomes 6 rows, so every payment is summed 3 times. Aggregate each child to the order level first, then join the one-row-per-order results.
Example (SQL)
WITH pay AS (
SELECT order_id, SUM(amount) AS paid FROM payments GROUP BY order_id
), ship AS (
SELECT order_id, COUNT(*) AS shipments FROM shipments GROUP BY order_id
)
SELECT o.order_date, SUM(p.paid) AS revenue, SUM(s.shipments) AS shipments
FROM orders o
LEFT JOIN pay p ON p.order_id = o.order_id
LEFT JOIN ship s ON s.order_id = o.order_id
GROUP BY o.order_date;
Common mistakes
- Fixing it with SUM(DISTINCT amount): two different payments with the same amount are then counted once.
- Testing only on orders with one shipment, where the bug is invisible.
How did you do? Your answer is saved in this browser and comes back for revision later.