Build a balance from charges and refunds
Your task
Return order_id, charge_cents, refund_cents, and net_cents for every ledger order. Show positive charge and refund totals, using zero when a kind is absent. Net is charges minus refunds. Sort by order ID.
A single order can have split charges or partial refunds. Count each ledger entry once in the balance.
Sample data
payment_ledger| entry_id | order_id | kind | amount_cents |
|---|---|---|---|
| 1 | 201 | charge | 2500 |
| 2 | 202 | charge | 1800 |
| 3 | 203 | charge | 1100 |
| 4 | 203 | charge | 2100 |
| 5 | 204 | charge | 5000 |
| 6 | 204 | refund | 5000 |
| 7 | 205 | charge | 2500 |
| 8 | 206 | charge | 4000 |
| 9 | 208 | charge | 1700 |
| 10 | 209 | charge | 2900 |
Preview of 10 of 13 rows
Expected output
| order_id | charge_cents | refund_cents | net_cents |
|---|---|---|---|
| 201 | 2500 | 0 | 2500 |
| 202 | 1800 | 0 | 1800 |
| 203 | 3200 | 0 | 3200 |
| 204 | 5000 | 5000 | 0 |
| 205 | 2500 | 0 | 2500 |
| 206 | 4000 | 500 | 3500 |
| 207 | 900 | 0 | 900 |
| 208 | 1700 | 0 | 1700 |
| 209 | 2900 | 0 | 2900 |
| 999 | 800 | 0 | 800 |
Show a hint
Use separate conditional sums for charge and refund entries, then subtract the two totals.
Data quality and reconciliation guide
Keep raw values available while you clean them
The staged_orders table is an import, so references, statuses, and amounts are text and may contain missing or malformed values. Trim whitespace before testing a field. An empty string after trimming can be turned into NULL to give missing data one representation.
SELECT import_id, NULLIF(TRIM(order_ref), '') AS clean_ref
FROM staged_orders
ORDER BY import_id;Compare records at the same grain
The payment ledger may have several charges or refunds for one order. Aggregate that ledger to one row per order before comparing it with shop_orders. Keep unmatched keys visible so a reconciliation reveals missing orders and missing payments.
SELECT order_id,
SUM(CASE WHEN kind = 'charge' THEN amount_cents ELSE -amount_cents END) AS net_cents
FROM payment_ledger
GROUP BY order_id
ORDER BY order_id;Worked solution
WITH totals AS (SELECT order_id,SUM(CASE WHEN kind='charge' THEN amount_cents ELSE 0 END) AS charge_cents,SUM(CASE WHEN kind='refund' THEN amount_cents ELSE 0 END) AS refund_cents FROM payment_ledger GROUP BY order_id) SELECT order_id,charge_cents,refund_cents,charge_cents-refund_cents AS net_cents FROM totals ORDER BY order_id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
