AVG()
Overview
The AVG()
window function calculates the average (arithmetic mean) of a set of numeric values within a window. This function allows you to compute averages over a set of rows that are related to the current row, such as rows within a partition of ordered set.
Syntax
The syntax for this function is as follows:
Parameters
expression
: column or expression that the function operates on (must be of numeric type)ROWS or RANGE
: (optional) frame specification to control which rows are included in the calculation relative to the current row
Example
For the needs of this section, we will use a simplified version of the film
table from the Pagila database, containing only the title
, length
and rating
columns. The complete schema for the film
table can be found on the
Pagila database website.
Rolling Average by Rating
The query below uses the AVG()
function to calculate the rolling average of length
as rows are ordered by rating
:
By executing the query above, we will get the following output:
Time Series: Rolling Average Length over Last 3 Ratings
In this example, we will demonstrate a time series-style rolling average using a window frame of the current row and the two preceding rows, ordered by rating. This simulates a moving average over a sliding window of 3 rows:
The query above calculates the average length over the current rating and the two previous ratings (based on ordering by rating) smoothing the fluctuations by averaging over a fixed-size window: