Fill gaps in monthly revenue
Your task
Return every month from January through April 2025 and its total receipt amount, using zero when there are no receipts. Sort chronologically.
Build a calendar spine first, then left join monthly totals so missing months still appear.
Sample data
receipts| id | sold_on | amount | channel | metadata |
|---|---|---|---|---|
| 1 | 2025-01-01 | 36 | ONLINE | {"currency":"EUR","tags":["gift","jazz"]} |
| 2 | 2025-01-16 | 22 | Store | {"currency":"EUR","tags":["indie"]} |
| 3 | 2025-01-31 | 54 | online | {"currency":"EUR","tags":["returning","bundle"]} |
| 4 | 2025-03-04 | 38 | STORE | {"currency":"EUR","tags":[]} |
| 5 | 2025-04-09 | 44 | Online | {"currency":"EUR","tags":["indie"]} |
Expected output
| start | COALESCE(t.revenue,0) |
|---|---|
| 2025-01-01 | 112 |
| 2025-02-01 | 0 |
| 2025-03-01 | 38 |
| 2025-04-01 | 44 |
Show a hint
Generate month starts recursively and join to receipt totals grouped by DATE(sold_on, 'start of month').
Optimization and capstones guide
Compare equivalent filters
A function on an indexed column can hide the key from a direct range lookup. The two predicates here select the same January dates in this dataset. Compare the plans and look for a constrained SEARCH on the second query.
EXPLAIN QUERY PLAN
SELECT id FROM receipts WHERE STRFTIME('%Y-%m', sold_on) = '2025-01';
EXPLAIN QUERY PLAN
SELECT id FROM receipts
WHERE sold_on >= '2025-01-01' AND sold_on < '2025-02-01';Continue from a stable key
OFFSET skips entries before the requested page. With keyset pagination, use the last ID from the previous page as a boundary. The order and boundary must use the same key. Use a unique tie-breaker if the leading sort column can repeat.
EXPLAIN QUERY PLAN
SELECT id, title FROM catalog
WHERE id > 500
ORDER BY id
LIMIT 5;Summarize first, compare second
Start reports by deciding what one result row represents. This report groups receipts by month, then compares monthly totals with LAG. If February has no receipts, the next row compares with January. Generate a calendar CTE and left join it when gaps need to appear explicitly.
WITH monthly AS (
SELECT STRFTIME('%Y-%m', sold_on) AS month, SUM(amount) AS total
FROM receipts
GROUP BY month
)
SELECT month, total, total - LAG(total) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;Worked solution
WITH RECURSIVE months(start) AS (VALUES ('2025-01-01') UNION ALL SELECT DATE(start,'+1 month') FROM months WHERE start<'2025-04-01'), totals AS (SELECT DATE(sold_on,'start of month') AS month,SUM(amount) AS revenue FROM receipts GROUP BY month) SELECT m.start,COALESCE(t.revenue,0) FROM months m LEFT JOIN totals t ON t.month=m.start ORDER BY m.start;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
