// window reference

SQL moving average

AVG over a ROWS frame of n preceding rows gives a trailing moving average; the first n-1 rows see a shorter window and average what exists.

カテゴリ
ウィンドウ
Returns
numeric
In this category
32 of 79

構文

AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい MySQL 8.0+
SQLite はい SQLite 3.25+
Oracle はい Supported under this name.

例

Any engine

-- 7-row trailing average
SELECT day, price,
       AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7
FROM prices;

PostgreSQL

-- calendar-based: 7 days, not 7 rows
SELECT day, price,
       AVG(price) OVER (ORDER BY day RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS ma7d
FROM prices;

知っておくと便利なこと

  • ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is 7 rows only when 7 rows exist; early rows average fewer.
  • Centred frames (BETWEEN 3 PRECEDING AND 3 FOLLOWING) need future rows, so today's value changes once tomorrow's data arrives. Use trailing frames for anything published daily.
  • Frame size is row count, not time: gaps in dates stretch the average across them. For calendar windows use RANGE with an interval on PostgreSQL, MySQL and Oracle; SQLite can use RANGE 6 PRECEDING over julianday(day); SQL Server needs a calendar spine.

Questions about Moving Average

Why is my moving average shorter at the start?

The frame cannot reach before the first row, so early rows average the rows that exist. To blank them, wrap it: CASE WHEN COUNT(*) OVER (same frame) = 7 THEN AVG(...) OVER (same frame) END.

Moving average over days or over rows?

ROWS counts observations (right when data is dense and regular); RANGE with an interval counts time (right when dates have gaps). Same query shape, different frame clause.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.