Total refund amounts in the ledger
Your task
Return refund_count and refunded_cents across all ledger entries of kind refund.
The payment ledger records a refund’s magnitude as positive and identifies its direction in kind.
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
| refund_count | refunded_cents |
|---|---|
| 2 | 5500 |
Show a hint
Filter to refunds and use COUNT and SUM.
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
SELECT COUNT(*) AS refund_count,SUM(amount_cents) AS refunded_cents FROM payment_ledger WHERE kind='refund';Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
