Finance reports revenue per month after subtracting refunds. Sales and refunds live in separate tables, and some months have no refunds at all.
Using CTEs, return one row per month that has sales: month (formatted YYYY-MM), gross_revenue, refunds (0 when there are none) and net_revenue (gross minus refunds), ordered by month.
Sample data
Table: sales_txns
10 row(s) · showing first 8
| txn_idINT | txn_dateDATE | amountNUMERIC(10,2) |
|---|---|---|
| 1 | 2026-08-04 | 12000.00 |
| 2 | 2026-08-19 | 8500.00 |
| 3 | 2026-09-03 | 15000.00 |
| 4 | 2026-09-21 | 9000.00 |
| 5 | 2026-09-28 | 4500.00 |
| 6 | 2026-10-07 | 21000.00 |
| 7 | 2026-10-15 | 6500.00 |
| 8 | 2026-10-30 | 11000.00 |
Table: refund_txns
5 row(s)
| refund_idINT | refund_dateDATE | amountNUMERIC(10,2) |
|---|---|---|
| 1 | 2026-08-22 | 1500.00 |
| 2 | 2026-09-10 | 2000.00 |
| 3 | 2026-09-29 | 500.00 |
| 4 | 2026-10-12 | 4200.00 |
| 5 | 2026-10-20 | 1800.00 |
sales_txns
- txn_idINT
- txn_dateDATE
- amountNUMERIC(10,2)
refund_txns
- refund_idINT
- refund_dateDATE
- amountNUMERIC(10,2)
- Step 1: Aggregate each table to month level in its own CTE; joining the raw tables directly would multiply rows and inflate the sums.
- Step 2: `DATE_TRUNC('month', ...)` gives a clean join key for both CTEs.
- Step 3: `LEFT JOIN` from sales keeps November, which has no refunds; `COALESCE(..., 0)` stops the net revenue from becoming NULL.
WITH monthly_sales AS (
SELECT DATE_TRUNC('month', txn_date) AS month_start,
SUM(amount) AS gross_revenue
FROM sales_txns
GROUP BY 1
),
monthly_refunds AS (
SELECT DATE_TRUNC('month', refund_date) AS month_start,
SUM(amount) AS refunds
FROM refund_txns
GROUP BY 1
)
SELECT TO_CHAR(s.month_start, 'YYYY-MM') AS month,
s.gross_revenue,
COALESCE(r.refunds, 0) AS refunds,
s.gross_revenue - COALESCE(r.refunds, 0) AS net_revenue
FROM monthly_sales s
LEFT JOIN monthly_refunds r ON r.month_start = s.month_start
ORDER BY s.month_start;More CTEs questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program