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_id | customer_id | amount |
|---|---|---|
| 1 | 100 | 400 |
| 2 | 100 | 100 |
| 3 | 200 | 250 |
shipments
order_id INTEGER, box INTEGER
| order_id | box |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
payments
order_id INTEGER, paid INTEGER
| order_id | paid |
|---|---|
| 1 | 200 |
| 1 | 200 |
| 2 | 100 |
| 3 | 250 |
- Do you need the shipments table at all? Every extra one-to-many join multiplies the rows.
- Aggregate payments to one row per order first, then join that to orders.
Expected output
| customer_id | order_total | paid_total |
|---|---|---|
| 100 | 500 | 500 |
| 200 | 250 | 250 |
Show solution
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.
Why this works
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.