0
0
SQLquery~5 mins

Moving averages with window frames in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a moving average in SQL?
A moving average calculates the average of a set of values over a specific range or window that moves through the data, helping to smooth out short-term fluctuations.
Click to reveal answer
beginner
What does the OVER() clause do in a moving average query?
The OVER() clause defines the window or set of rows the function operates on, allowing calculation of moving averages over a specific range of rows.
Click to reveal answer
intermediate
Explain the difference between ROWS BETWEEN and RANGE BETWEEN in window frames.
ROWS BETWEEN counts physical rows before and after the current row, while RANGE BETWEEN counts rows based on value ranges in the ordering column.
Click to reveal answer
intermediate
Write a simple SQL query to calculate a 3-day moving average of sales ordered by date.
SELECT date, sales, AVG(sales) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM sales_table;
Click to reveal answer
intermediate
Why use moving averages with window frames instead of grouping data?
Moving averages with window frames keep all rows and calculate averages dynamically over a sliding window, unlike grouping which aggregates rows into fewer results.
Click to reveal answer
Which SQL clause defines the window for a moving average calculation?
AHAVING
BGROUP BY
CWHERE
DOVER()
What does ROWS BETWEEN 2 PRECEDING AND CURRENT ROW mean in a window frame?
AInclude only the current row
BInclude the current row and the two rows after it
CInclude the current row and the two rows before it
DInclude all rows in the table
Which function is commonly used to calculate moving averages in SQL?
ASUM()
BAVG()
CCOUNT()
DMAX()
What is the main benefit of using window functions for moving averages?
AThey allow calculations without collapsing rows
BThey reduce the number of rows returned
CThey sort the data automatically
DThey filter rows based on conditions
If you want a moving average over the last 7 days including today, which window frame would you use?
AROWS BETWEEN 6 PRECEDING AND CURRENT ROW
BROWS BETWEEN CURRENT ROW AND 6 FOLLOWING
CRANGE BETWEEN 6 PRECEDING AND CURRENT ROW
DGROUP BY date
Describe how to calculate a moving average using SQL window functions.
Think about how to tell SQL which rows to include for each average.
You got /4 concepts.
    Explain the difference between ROWS and RANGE in window frames for moving averages.
    Consider how the window moves when data has duplicates or gaps.
    You got /4 concepts.