🧠 Rolling Averages: Smooth Out the Trend

Xorthax has now seen totals that build over time. But sometimes a running total gets too large to be useful.

Instead of asking “how much so far?”, he wants to ask:

“What’s the average over the last few rows?”

That’s a rolling average.




🚀 Rolling Averages with AVG() OVER()

A rolling average calculates an average across a small window that moves row by row.

AVG(column) OVER (
  ORDER BY column
  ROWS BETWEEN n PRECEDING AND CURRENT ROW
)

This works because:

  • ORDER BY defines the sequence
  • The frame limits which rows are included
  • The average is recalculated at each row



📊 Example: Average of the Current Row and Two Before It

🧾 Sample Data

OrderDate Amount
2024-01-01100
2024-01-05150
2024-01-10200
2024-01-1550

SELECT OrderDate, Amount,
       AVG(Amount) OVER (
         ORDER BY OrderDate
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ) AS RollingAvg
FROM Orders;

Result:

OrderDate Amount RollingAvg
2024-01-01100100.0
2024-01-05150125.0
2024-01-10200150.0
2024-01-1550133.3

Each row shows the average for a small moving window, not the entire dataset.




🧠 What’s Happening Here?

ORDER BY OrderDate puts the rows in sequence from earliest to latest.

Then the frame tells SQL which rows to include for each calculation.

In this example, the frame includes:

  • The current row
  • The two rows before it

That means the window slides forward one row at a time.

Early rows use fewer values because there aren’t yet two previous rows available.

This is what makes rolling averages useful: they smooth out short-term ups and downs without using all rows in the table.




🧪 Practice What You Just Learned

3-Order Rolling Average

For each order, calculate the average totalamount over the current order and the two previous orders based on orderdate.


Tables Used
orders
ColumnType
orderidbigint
customeridbigint
orderdatetimestamp without time zone
totalamountdouble precision
statustext
Expected Output
Column
orderid
orderdate
totalamount
rolling_avg
Write Your Query:



➡️ Next Step

So far, you’ve used the most common frame patterns.

Next, you’ll look at more window frame options, including ways to look forward and define broader ranges.




Want to go deeper?