Month-over-Month Change
For each month of 2025, return month (like '2025-03'), deposited_cents (sum of deposits that month), previous_cents (the previous month's value, NULL for the first month) and change_cents (the difference, NULL for the first month). Only kind = 'deposit' counts. Sort by month.
Hint 1
Summarise by month in a CTE first, then use LAG(deposited_cents) OVER (ORDER BY month).
Reference solution
WITH monthly AS (
SELECT STRFTIME('%Y-%m', txn_date) AS month, SUM(amount_cents) AS deposited_cents
FROM transactions
WHERE kind = 'deposit' AND txn_date BETWEEN '2025-01-01' AND '2025-12-31'
GROUP BY STRFTIME('%Y-%m', txn_date)
)
SELECT month,
deposited_cents,
LAG(deposited_cents) OVER (ORDER BY month) AS previous_cents,
deposited_cents - LAG(deposited_cents) OVER (ORDER BY month) AS change_cents
FROM monthly
ORDER BY month;
LAG(x) returns the value of x from the previous row in the window order, LEAD(x) from the next one. The first row has no previous row, so you get NULL (or a default if you pass one: LAG(x, 1, 0)). Period-over-period comparison is the single most common use of LAG in business reports. The monthly summary comes first because window functions work on the rows they are given.