Moving average
AVG over a sliding frame of the last N rows, the usual smoothing line on a trend chart.
The task
You want a 7-point moving average of order amounts to smooth out daily noise in a chart.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT order_date, id, amount,
AVG(amount) OVER (ORDER BY order_date, id
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_last_7
FROM orders
ORDER BY order_date, id;
Como funciona
The frame 6 PRECEDING AND CURRENT ROW slides a seven-row window over the data; AVG averages whatever falls inside it, including the shorter windows at the start of the series. ROWS counts physical rows, so gaps in the data do not stretch the window back in time. Add PARTITION BY if the average should restart per group, such as per customer.
Variations
Trailing 7 calendar days (PostgreSQL)
PostgreSQLSELECT order_date,
AVG(amount) OVER (ORDER BY order_date
RANGE BETWEEN INTERVAL '6 days' PRECEDING
AND CURRENT ROW) AS avg_7_days
FROM orders
ORDER BY order_date;
Questions that come up
Why do the first rows have a shorter window?
There are fewer than seven rows before them, so the frame holds only the rows that exist. All five engines average what is in the frame rather than returning NULL; wrap the result in CASE WHEN ROW_NUMBER() OVER (ORDER BY order_date, id) >= 7 THEN ... END if you want to hide the warm-up rows.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.