×

sql · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

sets exactly which rows a window looks at.

One busy day can hide a trend. A smooths it out: each day shows the average of the last few days, and the window slides along with you.

The rows a window looks at for each row are its . ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means this row and the two before it, so AVG(amount) over that frame is a three-row average.

Other edges work too, such as 1 FOLLOWING or UNBOUNDED PRECEDING. Near the start the frame holds fewer rows, so the first row averages only itself.

SELECT day, amount,
  ROUND(AVG(amount) OVER (
    ORDER BY day
    ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
  ), 1) AS avg_3
FROM takings
ORDER BY day;

With 4 June missing, three rows are not quite three days. Unit 4 shows how to fill the gap.