InterviewPrepKit

Home / SQL / Window Functions

3-Day Trailing Moving Average

hard
Solving tips
  • A trailing moving average is AVG(...) OVER (ORDER BY time ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) — an N-day window uses N-1 PRECEDING.
  • The frame counts rows physically with ROWS, so early rows average fewer values (a partial window) rather than NULL.
  • Use ROWS (row count) not RANGE (value range) when your window is a fixed number of observations.

You have daily revenue and need a smoothed 3-day trailing moving average to damp out day-to-day noise.

Schema

CREATE TABLE sales (
    day     DATE,
    revenue INT
);
dayrevenue
2024-05-01100
2024-05-02200
2024-05-03300
2024-05-04400
2024-05-05500
2024-05-06600
2024-05-07700

Task

For each day return revenue and moving_avg_3d: the average of the current day’s revenue and the two days before it, rounded to 2 decimals. The first two days average whatever rows are available (a partial window), not NULL. Order by day ascending.

Expected output

dayrevenuemoving_avg_3d
2024-05-01100100.00
2024-05-02200150.00
2024-05-03300200.00
2024-05-04400300.00
2024-05-05500400.00
2024-05-06600500.00
2024-05-07700600.00
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.