← All SQL interview questions

Monthly net revenue after refunds

MediumCTEsPayPalRazorpay

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_idINTtxn_dateDATEamountNUMERIC(10,2)
12026-08-0412000.00
22026-08-198500.00
32026-09-0315000.00
42026-09-219000.00
52026-09-284500.00
62026-10-0721000.00
72026-10-156500.00
82026-10-3011000.00

Table: refund_txns

5 row(s)

refund_idINTrefund_dateDATEamountNUMERIC(10,2)
12026-08-221500.00
22026-09-102000.00
32026-09-29500.00
42026-10-124200.00
52026-10-201800.00