AdvancedJoins

Order and payment totals without double counting

Task

Each order can have several shipments and several payments. Return each customer's total order amount and total payment amount. Columns: customer_id, order_total, paid_total.

Row order does not matter. Column names do not have to match. SQLite dialect.

Tables

orders

order_id INTEGER, customer_id INTEGER, amount INTEGER

order_idcustomer_idamount
1100400
2100100
3200250

shipments

order_id INTEGER, box INTEGER

order_idbox
11
12
21
31
32
33

payments

order_id INTEGER, paid INTEGER

order_idpaid
1200
1200
2100
3250
Expected output
customer_idorder_totalpaid_total
100500500
200250250
Show solution
SQL
WITH paid AS (
  SELECT order_id, SUM(paid) AS paid FROM payments GROUP BY order_id
)
SELECT o.customer_id,
       SUM(o.amount) AS order_total,
       SUM(COALESCE(p.paid, 0)) AS paid_total
FROM orders o
LEFT JOIN paid p ON p.order_id = o.order_id
GROUP BY o.customer_id;

Joining two one-to-many tables multiplies rows: order 1 has 2 payments, so joining payments alone already counts its 400 twice. Pre-aggregate each child table to the parent's grain before joining, and drop joins you do not need.

The full explanation, with more examples, is in the question Order and payment totals without double counting.