Stop a refund JOIN from multiplying sales Original fictional practice data · 2026-11-11 · CC BY 4.0 BRIEF A marketplace has separate order lines and refund events. Produce one ledger row per order before finance compares net sales. CONTRACT 1. Aggregate sales lines and refunds separately before joining. Amounts are integer USD cents. 2. Collapse identical refund events using all three fields. Refunds for unknown orders go to a separate review; exclude them from this order ledger. 3. Keep all four order IDs, including zero-value A13. Return order_id, gross_cents, refund_cents, net_cents sorted by order_id. METHOD First inspect A10: two sale lines and two unique refunds create four rows in a raw join. Deduplicate events, sum each table to order grain, then LEFT JOIN onto sales. Use COALESCE for orders without refunds and verify the net total independently. COMMON MISTAKE SUM(DISTINCT amount_cents) would discard legitimate equal-value lines. Deduplicate event identity, not money. INDEPENDENT CROSS-CHECK The orphan R4 is 700 cents and is not part of the 27,500-cent net ledger. DELIVER A checked output CSV and a handoff note explaining the exception policy. Use setup.sql in SQLite or import each table CSV into your spreadsheet. expected.csv is the complete reference result; an empty CSV field represents SQL NULL. The browser executes SQLite, not Excel formulas. XLOOKUP is unavailable in Excel 2016 and 2019. Sources for function behavior: https://www.sqlite.org/lang_select.html and https://support.microsoft.com/en-us/excel/functions/xlookup-function (checked 2026-11-11). Rates, dates and policies here are exercise assumptions.