// window reference

SQL AVG with OVER

Averages the window frame or partition and keeps every row: the group mean next to each value for variance-from-average analysis.

類別
視窗
Returns
numeric
In this category
24 of 79

語法

AVG(x) OVER (PARTITION BY g) | 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

SELECT department, salary,
       salary - AVG(salary) OVER (PARTITION BY department) AS vs_dept_avg
FROM employees;

Any engine

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

小知識

  • On SQL Server, AVG of an int column returns int: AVG(x) over 1 and 2 is 1, not 1.5. PostgreSQL returns numeric, MySQL decimal, SQLite always a float, Oracle NUMBER. Cast on SQL Server, in window form too.
  • NULL rows are skipped in the numerator and denominator alike; rows where x is NULL contribute nothing, they do not drag the average down.
  • ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is a 7-row trailing average, not a 7-day one: missing dates stretch it over a longer period.

Questions about AVG OVER

Why is AVG OVER returning whole numbers?

You are on SQL Server and the column is an integer type: AVG returns the input type there. Cast: AVG(x * 1.0) OVER (...) or AVG(CAST(x AS DECIMAL(10,2))) OVER (...). The other four engines already return a fractional result.

AVG OVER or moving average: which do I have?

AVG(x) OVER (PARTITION BY g) is one average per group; adding ORDER BY with a frame makes it row-by-row. Both can appear in one query with different OVER clauses.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.