How does this query calculate the rolling 7‑day average revenue using a window function?
💡 Model Answer
The query uses a window function to compute a rolling 7‑day average of revenue. The AVG() aggregate is applied over a window frame defined by ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW. Because the frame uses ROWS, the window counts the current row and the six rows that come before it in the order_date sequence, regardless of gaps in dates. This is ideal for daily data where you want a fixed‑size window of rows. If you used RANGE BETWEEN 6 PRECEDING AND CURRENT ROW, the window would include all rows whose order_date is within 6 days of the current row, which could produce a variable number of rows if some days are missing. The result is a new column rolling_7day_avg that shows the average revenue for the last seven days up to each order_date. The complexity is O(n) because each row is processed once and the window frame is maintained with a sliding window. This pattern is common in time‑series analytics, trend analysis, and KPI dashboards. In practice, you might also partition by a dimension such as product or region to compute rolling averages per group. The window function is efficient because the database engine can compute the running sum and count incrementally, avoiding a self‑join or subquery.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500