Moving averages and running shares
Moving average: AVG(x) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). Running share: SUM(x) OVER (ORDER BY x DESC) / SUM(x) OVER (). With only ORDER BY, the default frame is RANGE, so tied rows are added together; add a second sort column or write ROWS.
Here's how monthly sales went: 743 in May, down to 310 in June, then back up to 820 in July. The boss asks, "So is business getting better or worse?" Month by month, all you see is ups and downs. This lesson uses window functions to smooth the bumps out, and then looks at which few products bring in most of the money.
Running total up to this month
In this step you go over the running total from the beginner course. SUM(sales) OVER (ORDER BY month) adds every row before it to each row:
1WITH monthly AS (2 SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(amount) AS sales3 FROM orders4 WHERE status = 'paid'5 GROUP BY month6)7SELECT month, sales,8 SUM(sales) OVER (ORDER BY month) AS running9FROM monthly10ORDER BY month;
| month | sales | running |
|---|---|---|
| 2025-01 | 36 | 36 |
| 2025-03 | 366 | 402 |
| 2025-04 | 126 | 528 |
| 2025-05 | 743 | 1271 |
| 2025-06 | 310 | 1581 |
| 2025-07 | 820 | 2401 |
| 2025-08 | 626 | 3027 |
| 2025-09 | 977 | 4004 |
| 2025-10 | 789 | 4793 |
| 2025-11 | 1042 | 5835 |
| 2025-12 | 588 | 6423 |
By the end of June, the shop had sold only 1581, about a quarter of the year. The second half of the year brought in the other three quarters. A running total only ever goes up, and it's what you use for "how much so far this year".
The last row of the running column is always equal to what?
The window's frame
In this step you learn the moving average: each month isn't looked at alone, but averaged together with the two months before it. That smooths out the ups and downs between months, so the trend is easier to see.
The key is to write a frame inside OVER: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, which means "from 2 rows back up to this row", 3 rows in all.
1WITH monthly AS (2 SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(amount) AS sales3 FROM orders4 WHERE status = 'paid'5 GROUP BY month6)7SELECT month, sales,8 ROUND(AVG(sales) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_39FROM monthly10ORDER BY month;
| month | sales | avg_3 |
|---|---|---|
| 2025-01 | 36 | 36.0 |
| 2025-03 | 366 | 201.0 |
| 2025-04 | 126 | 176.0 |
| 2025-05 | 743 | 411.7 |
| 2025-06 | 310 | 393.0 |
| 2025-07 | 820 | 624.3 |
| 2025-08 | 626 | 585.3 |
| 2025-09 | 977 | 807.7 |
| 2025-10 | 789 | 797.3 |
| 2025-11 | 1042 | 936.0 |
| 2025-12 | 588 | 806.3 |
sales goes up and down, but from April on avg_3 climbs almost all the way, peaking at 936 in November. Business is getting better.
| month | sales |
|---|---|
| 2025-06 | 310 |
| 2025-07 | 820 |
| 2025-08 | 626 |
| 2025-09 | 977 |
| 2025-10 | 789 |
AVG(sales) OVER (… ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)| month | sales | avg_3 |
|---|---|---|
| 2025-09 | 977 | 807.7 |
Other ways to write a frame: n FOLLOWING (n rows ahead), UNBOUNDED PRECEDING (from the first row), UNBOUNDED FOLLOWING (to the last row).
To average the last 7 days, day by day, how many rows back should the frame go?
1AVG(dau) OVER (ORDER BY day ROWS BETWEEN PRECEDING AND CURRENT ROW)When the frame isn't full
In this step you meet two traps of moving averages. Look at the same result again, this time also counting how many rows are in each frame:
1WITH monthly AS (2 SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(amount) AS sales3 FROM orders4 WHERE status = 'paid'5 GROUP BY month6)7SELECT month, sales,8 COUNT(*) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS n,9 ROUND(AVG(sales) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_310FROM monthly11ORDER BY month12LIMIT 4;
| month | sales | n | avg_3 |
|---|---|---|---|
| 2025-01 | 36 | 1 | 36.0 |
| 2025-03 | 366 | 2 | 201.0 |
| 2025-04 | 126 | 3 | 176.0 |
| 2025-05 | 743 | 3 | 411.7 |
Trap one: the first frames aren't full. January has no rows before it, so its "3-month average" is just January itself, and March has only 2 rows. You can't compare these averages with the later ones. Reports often leave the rows with a short frame blank: CASE WHEN n = 3 THEN avg_3 END.
Trap two: the frame counts rows, not months. March's frame holds January and March, because February had no orders, so it has no row at all (you saw this in lesson 2). "2 rows back" jumps over February. So before working out a moving average, fill in the missing months with 0 first.
April's avg_3 is the average of which months?
Active users each day
In this step you use it on daily data. The events table records what users did in the app during the first two weeks of December. The number of different users who logged in on a day is called daily active users (DAU). DAU jumps around a lot from day to day, so a 7-day average is steadier:
1WITH daily AS (2 SELECT day, COUNT(DISTINCT user_id) AS dau3 FROM events4 GROUP BY day5)6SELECT day, dau7FROM daily8ORDER BY day;
| day | dau |
|---|---|
| 2025-12-01 | 7 |
| 2025-12-02 | 7 |
| 2025-12-03 | 6 |
| 2025-12-04 | 10 |
| 2025-12-05 | 9 |
| 2025-12-06 | 7 |
| 2025-12-07 | 8 |
| 2025-12-08 | 9 |
| 2025-12-09 | 4 |
| 2025-12-10 | 11 |
| 2025-12-11 | 7 |
| 2025-12-12 | 13 |
| 2025-12-13 | 7 |
| 2025-12-14 | 5 |
December 9 had only 4 people, and the 12th had 13. Look at any single day, and you can easily draw the wrong conclusion.
7-day average DAU
✓Next to each day's DAU, add a column avg_7: the average DAU of the last 7 days (that day included), rounded to 1 decimal place. Three columns: day, dau and avg_7. Show only December 7 and later (the days with a full 7-day frame).
| day | dau | avg_7 |
|---|---|---|
| 2025-12-07 | 8 | 7.7 |
| 2025-12-08 | 9 | 8.0 |
| 2025-12-09 | 4 | 7.6 |
| 2025-12-10 | 11 | 8.3 |
| 2025-12-11 | 7 | 7.9 |
| 2025-12-12 | 13 | 8.4 |
| 2025-12-13 | 7 | 8.4 |
| 2025-12-14 | 5 | 8.0 |
1WITH daily AS (2 SELECT day, COUNT(DISTINCT user_id) AS dau3 FROM events4 GROUP BY day5),6smoothed AS (7 SELECT day, dau8 FROM daily9)10SELECT day, dau, avg_711FROM smoothed12WHERE day >= '2025-12-07'13ORDER BY day;
The 80/20 rule: running share
In this step you answer "which products bring in most of the money?" Sort the products by sales from highest to lowest, keep a running total, and divide it by the overall total: that's the running share. SUM(sales) OVER () has nothing in the parentheses, so the frame is the whole table, and you get the overall total:
1WITH product_sales AS (2 SELECT p.id, p.name, SUM(oi.qty * oi.price) AS sales3 FROM orders AS o4 JOIN order_items AS oi ON oi.order_id = o.id5 JOIN products AS p ON p.id = oi.product_id6 WHERE o.status = 'paid'7 GROUP BY p.id, p.name8)9SELECT name, sales,10 ROUND(100 * SUM(sales) OVER (ORDER BY sales DESC, id) / SUM(sales) OVER (), 1) AS cum_pct11FROM product_sales12ORDER BY sales DESC, id;
| name | sales | cum_pct |
|---|---|---|
| Headphones | 1680 | 26.2 |
| Speaker | 1560 | 50.4 |
| Cushion | 666 | 60.8 |
| Desk lamp | 630 | 70.6 |
| Charger | 475 | 78.0 |
| Water bottle | 300 | 82.7 |
| Coffee beans | 300 | 87.4 |
| Desk calendar | 288 | 91.8 |
| Tea box | 220 | 95.3 |
| Notebook | 144 | 97.5 |
| USB cable | 108 | 99.2 |
| Pen pack | 52 | 100.0 |
Of the 12 products, Headphones and Speaker alone make up half the sales (50.4%), and the top 4 make up 70%. This is the famous 80/20 rule: a few things carry most of the business. Stock and promotion should look after them first.
The boss says, "I only want to keep a close eye on a few products, but together they must make up more than three quarters of the year's sales." Looking at the cum_pct column, what's the smallest number of products to watch?
Running totals with ties
In this step you meet the sneakiest trap of windows. Why does ORDER BY sales DESC, id in the running share have an id in it? Take it out and see:
Water bottle and Coffee beans both sold 300. Without id, what's the running value of their two rows?
1WITH product_sales AS (2 SELECT p.id, p.name, SUM(oi.qty * oi.price) AS sales3 FROM orders AS o4 JOIN order_items AS oi ON oi.order_id = o.id5 JOIN products AS p ON p.id = oi.product_id6 WHERE o.status = 'paid'7 GROUP BY p.id, p.name8)9SELECT id, name, sales,10 SUM(sales) OVER (ORDER BY sales DESC) AS running11FROM product_sales12WHERE sales BETWEEN 288 AND 47513ORDER BY sales DESC, id;
ORDER BY and no frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE works by value: rows with the same sort value count as the same position and are added in together. Both rows are 300, so each one includes the other: 475 + 300 + 300 = 1075.There are two fixes: add a column that never repeats (like id) to ORDER BY, so every row has its own position; or write the frame out as ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. ROWS counts rows, adding them one at a time.
What you learned
- Running total:
SUM(x) OVER (ORDER BY time). The last row equals the overall total, which you can use as a check. - Moving average:
AVG(x) OVER (ORDER BY time ROWS BETWEEN n PRECEDING AND CURRENT ROW), n + 1 rows in all. The last 7 days is6 PRECEDING. - The first frames aren't full, so their averages can't be compared with the later ones. A frame counts rows, so fill in missing days or months first.
- Work out the window inside
WITHfirst, then pick rows withWHEREoutside. Otherwise the frames lose rows. - Running share:
SUM(x) OVER (ORDER BY x DESC) / SUM(x) OVER ().OVER ()is the whole table. - With only
ORDER BY, the default frame isRANGE, and tied rows are added together. Add a sort column that never repeats, or writeROWS.