Window Functions · Problem 76 of 118

Moving Average of Deposits

HardWindow FunctionsBank data

Using the monthly deposit totals of 2025 (only kind = 'deposit'), return month, deposited_cents and moving_avg_cents: the average of the current and the two previous months (fewer months at the start of the year), rounded to a whole number. Sort by month.

Hint 1

A frame limits the rows a window function looks at: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.

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,
       ROUND(AVG(deposited_cents) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)) AS moving_avg_cents
FROM monthly
ORDER BY month;

The frame decides which rows around the current row the function sees. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means "this row and the two before it". At the start of the series there are not enough rows, so the first averages use fewer values: decide whether that is acceptable or whether to hide those rows. A ROWS frame counts rows, not calendar months, so if a month were missing from the data the "previous two rows" would reach further back in time: fill gaps first with a generated calendar.