Rolling Average Window Three Period

Compute a three period rolling average using SQL window functions with a sliding frame between preceding and following rows.

SqlData Fetching

Code

sqlsnippet
9 lines
SELECT
  date,
  value,
  AVG(value) OVER (
    ORDER BY date
    ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
  ) AS rolling_avg_3
FROM measurements
ORDER BY date;

How it works

At its core this is a single SELECT statement against measurements.

Breaking the statements into their working parts: AVG aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

Points of care

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

The measurements table is the working surface here.

Core lines

SELECT
  date,
  value,
  AVG(value) OVER (
    ORDER BY date
    ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
  ) AS rolling_avg_3
FROM measurements
ORDER BY date;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `measurements`.