Kodewick
Start learning →
Moving averages and running shares5 / 12

Moving averages and running shares

Lesson 5 of 12 · Part 2 · Window functions at work · about 20 minutes

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:

main.sql
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;
Output
monthsalesrunning
2025-013636
2025-03366402
2025-04126528
2025-057431271
2025-063101581
2025-078202401
2025-086263027
2025-099774004
2025-107894793
2025-1110425835
2025-125886423
11 rows

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".

Choose one

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.

main.sql
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;
Output
monthsalesavg_3
2025-013636.0
2025-03366201.0
2025-04126176.0
2025-05743411.7
2025-06310393.0
2025-07820624.3
2025-08626585.3
2025-09977807.7
2025-10789797.3
2025-111042936.0
2025-12588806.3
11 rows

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.

monthly
monthsales
2025-06310
2025-07820
2025-08626
2025-09977
2025-10789
AVG(sales) OVER (… ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
the 2025-09 row
monthsalesavg_3
2025-09977807.7
Each row's frame: from 2 rows back up to this row, averaged together

Other ways to write a frame: n FOLLOWING (n rows ahead), UNBOUNDED PRECEDING (from the first row), UNBOUNDED FOLLOWING (to the last row).

Fill inTap one to fill a blank; tap a blank to take it back

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:

main.sql
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;
Output
monthsalesnavg_3
2025-0136136.0
2025-033662201.0
2025-041263176.0
2025-057433411.7
4 rows

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.

Choose one

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:

main.sql
1WITH daily AS (2    SELECT day, COUNT(DISTINCT user_id) AS dau3    FROM events4    GROUP BY day5)6SELECT day, dau7FROM daily8ORDER BY day;
Output
daydau
2025-12-017
2025-12-027
2025-12-036
2025-12-0410
2025-12-059
2025-12-067
2025-12-078
2025-12-089
2025-12-094
2025-12-1011
2025-12-117
2025-12-1213
2025-12-137
2025-12-145
14 rows

December 9 had only 4 people, and the 12th had 13. Look at any single day, and you can easily draw the wrong conclusion.

Exercise 1

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).

It should print
daydauavg_7
2025-12-0787.7
2025-12-0898.0
2025-12-0947.6
2025-12-10118.3
2025-12-1177.9
2025-12-12138.4
2025-12-1378.4
2025-12-1458.0
8 rows
exercise1.sql
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;
Output
Press Run or Ctrl+Enter

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:

main.sql
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;
Output
namesalescum_pct
Headphones168026.2
Speaker156050.4
Cushion66660.8
Desk lamp63070.6
Charger47578.0
Water bottle30082.7
Coffee beans30087.4
Desk calendar28891.8
Tea box22095.3
Notebook14497.5
USB cable10899.2
Pen pack52100.0
12 rows

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.

Choose one

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:

Choose oneA wrong guess is fine

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;

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 is 6 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 WITH first, then pick rows with WHERE outside. 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 is RANGE, and tied rows are added together. Add a sort column that never repeats, or write ROWS.
Practise what this lesson taught#022SUM() OVER (ORDER BY …)Running totalBasic#025SUM() OVER (PARTITION BY … ORDER BY …)Spent so farBasic#036ROW_NUMBER() + COUNT(*) OVER ()Median orderMini challengeAll 50 SQL problems →