Joins, grain and reconciliation
The decision
An analyst joins orders to support contacts. Orders have one row per order, while contacts have one row per interaction. Joining first and summing money can multiply revenue. Identify the grain of each table and the intended output before writing the query.
Synthetic case data
order_id,customer,amount,contact_count
1,A,40,2
2,A,20,0
3,B,30,1
Work it through
Before reading the worked analysis, identify the unit of observation, required quantities and missing information. Write your own answer, including units and a limitation.
Worked analysis
True revenue is 40+20+30=90. An inner join to contacts produces two rows for order 1, no row for order 2 and one row for order 3, giving a misleading sum of 110. Aggregate contacts by order_id first, then LEFT JOIN the result to orders. COALESCE(contact_count,0) means no matched contacts; it does not turn missing revenue into observed zero. Reconcile order count 3 and revenue 90. SUM(DISTINCT amount) is not a general repair: two legitimate orders can have the same amount.
Independent challenge
Write an orders CTE, a contact-count CTE and a final LEFT JOIN. Return one row per customer with revenue and contact totals. Add a test order with no contacts and another contact on order 3; existing revenue must remain 90. State the SQL dialect used.
Acceptance checks
A totals 60 with two contacts; B totals 30 with one contact. Retain zero-contact orders and test unique order keys before aggregation.
Further reading
Official reference. This original academy exercise uses synthetic data; the reference provides background and does not endorse the academy.
