SQL Moving Averages: Row and Calendar Windows
Overview
A moving average summarizes a limited window near each observation. A three-observation window is not necessarily a three-day window when dates are missing or repeated.
First example
SELECT id, AVG(value) OVER w AS moving_avg, COUNT(value) OVER w AS knownFROM window_readings WHERE sensor = 'A'WINDOW w AS (ORDER BY day, id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 10, 1 ], [ 2, 12, 2 ], [ 3, 12, 2 ], [ 4, 17, 2 ]]How it works
Example one averages the current and preceding two rows, ignoring NULL measurements. COUNT(value) shows the denominator actually used. At the beginning of a partition there may be fewer than three rows. Example two uses SQLite julianday(day) as the numeric ordering key and a RANGE of two days preceding, inclusive of today. On January 5 the last three rows span Jan 3–5, and the calendar window also includes Jan 3; on Jan 4 the row window includes Jan 1 but the calendar window does not. PostgreSQL can use an interval offset with a date/timestamp ordering expression; julianday is SQLite-specific.
Practical example
SELECT id, AVG(value) OVER (ORDER BY julianday(day) RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) AS daily_avgFROM window_readings WHERE sensor = 'A' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 10 ], [ 2, 12 ], [ 3, 14 ], [ 4, 17 ]]Practice and mistakes
Change the row frame to one preceding and one following; predict the average at each edge. For a strict three-day report including missing dates as separate rows, build a calendar spine and explicitly decide whether missing measurements mean zero or unknown. Do not blindly divide by three. PostgreSQL interval example in the dialect evidence is not executed.
PostgreSQL 17 example — NOT RUN
SELECT id, AVG(value) OVER (ORDER BY CAST(day AS DATE) RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW) AS daily_avgFROM window_readings WHERE sensor = 'A' ORDER BY id;Expected result, not executed: [[1, 10], [2, 12], [3, 14], [4, 17]]