Database Query Writer | SQL

SQL Rolling Average Calculation using Window Functions

SQL query calculating rolling average of a column over a specified time frame using window functions. Input: date_column, value_column. Output: date_column, value_column, rolling_avg.


Empty image or helper icon

Prompt

Can you provide a query that utilizes window functions in SQL to calculate a rolling average of a specific column over a specified time frame?

Answer

Query Using Window Functions to Calculate Rolling Average

-- Query to calculate rolling average using window functions
SELECT
    date_column,
    value_column,
    AVG(value_column) OVER (ORDER BY date_column ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rolling_avg
FROM
    your_table_name
ORDER BY
    date_column;

Explanation:

  • The query calculates a rolling average of a specific column (value_column) over a specified time frame.
  • date_column is the column representing the dates.
  • value_column is the column for which the rolling average needs to be calculated.
  • OVER (ORDER BY date_column ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) defines the window frame for the average calculation. In this case, it calculates the average of the current row and the two preceding rows.
  • The result includes date_column, original value_column, and the calculated rolling_avg.
  • your_table_name should be replaced with the actual name of the table in your database.
  • The result set is ordered by date_column to show the data in chronological order.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

SQL query calculating rolling average of a column over a specified time frame using window functions. Input: date_column, value_column. Output: date_column, value_column, rolling_avg.