Return each 2026 month and the rolling average of monthly transaction totals over that month and the two before it,…
SQLLevel: IntermediateCore interview patterns
Return each 2026 month and the rolling average of monthly transaction totals over that month and the two before it, rounded to 2 decimals, in order.
Table definitions (from the source exercise):
CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY, account_id INTEGER, transaction_date TEXT, amount REAL, merchant_category TEXT);
Hints
- Write an interleaving of two concurrent operations.
- Which observations does the isolation level permit, and what happens on a mid-operation failure?
Answer
Approach: AVG(total) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) on a monthly CTE.
WITH monthly AS (
SELECT DATE_FORMAT(transaction_date, '%Y-%m') AS m, SUM(amount) AS total
FROM transactions
GROUP BY m
)
SELECT m,
ROUND(AVG(total) OVER (ORDER BY m
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS rolling_avg_3m
FROM monthly
ORDER BY m;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT