Bird
0
0

Which SQL query correctly computes a moving average of revenue over the last 3 rows ordered by transaction_date?

easy📝 Syntax Q3 of 15
SQL - Advanced Window Functions
Which SQL query correctly computes a moving average of revenue over the last 3 rows ordered by transaction_date?
ASELECT transaction_date, revenue, AVG(revenue) OVER (ORDER BY transaction_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM transactions;
BSELECT transaction_date, revenue, AVG(revenue) OVER (ORDER BY transaction_date ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING) AS moving_avg FROM transactions;
CSELECT transaction_date, revenue, AVG(revenue) OVER (PARTITION BY transaction_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM transactions;
DSELECT transaction_date, revenue, AVG(revenue) OVER (ORDER BY transaction_date RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM transactions;
Step-by-Step Solution
Solution:
  1. Step 1: Understand the window frame

    The clause ROWS BETWEEN 2 PRECEDING AND CURRENT ROW includes the current row and the two previous rows.
  2. Step 2: Check the ORDER BY clause

    Ordering by transaction_date ensures the rows are processed in date order.
  3. Step 3: Verify syntax correctness

    SELECT transaction_date, revenue, AVG(revenue) OVER (ORDER BY transaction_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM transactions; correctly uses ROWS BETWEEN 2 PRECEDING AND CURRENT ROW with ORDER BY transaction_date.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Window frame must be between preceding and current row [OK]
Quick Trick: Use ROWS BETWEEN 2 PRECEDING AND CURRENT ROW for last 3 rows [OK]
Common Mistakes:
  • Using FOLLOWING instead of PRECEDING in window frame
  • Omitting ORDER BY inside OVER() clause
  • Using PARTITION BY incorrectly for this calculation
  • Confusing RANGE with ROWS frame specification

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes