Running totals and moving averages with windows
SQL
-- PostgreSQL: running totals and rolling averages with window functions.
SELECT day,
amount,
SUM(amount) OVER (ORDER BY day) AS running_total,
ROUND(AVG(amount) OVER (
ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2) AS avg_7_days
FROM daily_sales
ORDER BY day;
-- Multiple series: restart the window for each account.
SELECT account_id,
day,
SUM(amount) OVER (
PARTITION BY account_id
ORDER BY day
) AS account_running_total
FROM daily_sales
ORDER BY account_id, day;