Here’s an example of how to calculate cumulative averages using the AVG function in SQL:
SELECT
value,
AVG(value) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_avg
FROM
your_table;
Let’s break down the query:
-
SELECT value
: Select the value column from your table. -
AVG(value) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
: Use the AVG function with the OVER clause to calculate the average. TheORDER BY date
specifies the order in which the calculation is performed, and theROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
indicates that the average should be calculated from the beginning of the table up to the current row. -
AS cumulative_avg
: Alias the calculated value as “cumulative_avg” to make it clear what the column represents. -
FROM your_table
: Specify the table name where the data is stored. Replaceyour_table
with the actual name of your table.
This query will return the original value column along with a new column called cumulative_avg, which represents the cumulative average up to each row.
#SQL #WindowFunctions