How do you compute moving or rolling averages in SQL using window functions?

Quick Overview

Asks how to compute moving or rolling averages in SQL with window functions. Tests the frame clause, the difference between ROWS and RANGE frames, and how missing dates and partial early windows change the result.

How do you compute moving or rolling averages in SQL using window functions?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

How do you compute moving or rolling averages in SQL using window functions? A typical case is a 7-day average of daily sales from a table with one row per date. ```hint Frame clause Look at the frame clause that can follow `ORDER BY` inside `OVER (...)`, and ask what it counts when some dates have no row. ``` ### What a Strong Answer Covers - The window function form: `AVG` with `ORDER BY` and an explicit frame that sets the window size - Trailing versus centered windows and when each one fits - How `ROWS` and `RANGE` frames differ, and how missing dates affect each - What happens to the first rows, which have fewer values than a full window ### Follow-up Questions - How would you return NULL instead of a partial average for the first six days? - The table has no row on days with zero sales. How do you get a correct 7-day average? - What does the query return if you leave out the frame clause and keep only `ORDER BY dt`? - How would you compute the 7-day average separately for each store?

Overview: Asks how to compute moving or rolling averages in SQL with window functions. Tests the frame clause, the difference between ROWS and RANGE frames, and how missing dates and partial early windows change the result.

PracHub logo
General
Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

How do you compute moving or rolling averages in SQL using window functions?

A typical case is a 7-day average of daily sales from a table with one row per date.

What a Strong Answer Covers Guidance

  • The window function form: AVG with ORDER BY and an explicit frame that sets the window size
  • Trailing versus centered windows and when each one fits
  • How ROWS and RANGE frames differ, and how missing dates affect each
  • What happens to the first rows, which have fewer values than a full window

Follow-up Questions Guidance

  • How would you return NULL instead of a partial average for the first six days?
  • The table has no row on days with zero sales. How do you get a correct 7-day average?
  • What does the query return if you leave out the frame clause and keep only ORDER BY dt ?
  • How would you compute the 7-day average separately for each store?