Snowflake SQL Tutorial 56 - Moving Averages in Snowflake

Snowflake SQL · Episode 56

In this post we are going to cover moving averages in Snowflake.

A moving average is an average taken over a small stretch of the series instead of the whole of it. For every month we take that month and the two before it, average the three, and report that figure against the month. Then we slide along one month and do it again. There is no moving-average function in Snowflake. We build it out of AVG and a window frame.

We will start with the raw monthly series and put a trailing three-month average next to it. Then we will go through the three things that go wrong when you do this on real data: the windows at the start are short, a trailing window lags the month it is reported against, and a frame counts rows rather than months. We will finish with a window measured in days, and with one average per customer.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 56 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

Everything on this page runs against the shared ORDERS table. Paste the script below into a worksheet and run it once.

Sample data
-- Creates the ORDERS table every query on this page uses.
-- Part of the shared sample-data script; run it once.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE ORDERS (
    ORDER_ID     INT,
    CUSTOMER_ID  INT,
    ORDER_DATE   DATE,
    SHIP_DATE    DATE,
    STATUS       VARCHAR,
    AMOUNT       NUMBER(10,2),
    QUANTITY     INT
);

INSERT INTO ORDERS VALUES
    (1001, 101, '2023-01-12', '2023-01-15', 'SHIPPED',   4200.00,  12),
    (1002, 102, '2023-01-28', '2023-02-02', 'SHIPPED',    890.50,   3),
    (1003, 101, '2023-02-14', '2023-02-16', 'SHIPPED',   6150.00,  20),
    (1004, 103, '2023-02-27', NULL,         'CANCELLED', 1500.00,   5),
    (1005, 104, '2023-03-09', '2023-03-14', 'SHIPPED',   2310.75,   8),
    (1006, 101, '2023-03-22', '2023-03-24', 'SHIPPED',   5020.00,  16),
    (1007, 105, '2023-04-05', '2023-04-11', 'SHIPPED',   7890.00,  25),
    (1008, 102, '2023-04-19', '2023-04-23', 'SHIPPED',   1120.00,   4),
    (1009, 103, '2023-05-02', '2023-05-06', 'SHIPPED',   3340.25,  11),
    (1010, 106, '2023-05-21', NULL,         'PENDING',    640.00,   2),
    (1011, 101, '2023-06-08', '2023-06-10', 'SHIPPED',   8100.00,  27),
    (1012, 104, '2023-06-25', '2023-06-30', 'SHIPPED',   1975.50,   7),
    (1013, 105, '2023-07-11', '2023-07-15', 'SHIPPED',   6420.00,  21),
    (1014, 102, '2023-07-29', '2023-08-03', 'RETURNED',   750.00,   3),
    (1015, 107, '2023-08-14', '2023-08-17', 'SHIPPED',   9250.00,  30),
    (1016, 103, '2023-08-30', '2023-09-04', 'SHIPPED',   2860.00,   9),
    (1017, 101, '2023-09-16', '2023-09-19', 'SHIPPED',   5540.00,  18),
    (1018, 106, '2023-10-03', '2023-10-08', 'SHIPPED',   1430.00,   5),
    (1019, 105, '2023-10-22', '2023-10-26', 'SHIPPED',   7015.00,  23),
    (1020, 107, '2023-11-07', '2023-11-10', 'SHIPPED',  10400.00,  34),
    (1021, 102, '2023-11-24', '2023-11-29', 'SHIPPED',    980.00,   4),
    (1022, 104, '2023-12-09', NULL,         'CANCELLED', 2250.00,   8),
    (1023, 101, '2023-12-27', '2023-12-30', 'SHIPPED',   6730.00,  22),
    (1024, 103, '2024-01-15', '2024-01-18', 'SHIPPED',   3910.00,  13),
    (1025, 107, '2024-01-31', '2024-02-05', 'SHIPPED',  11200.00,  36),
    (1026, 105, '2024-02-17', '2024-02-21', 'SHIPPED',   8340.00,  27),
    (1027, 106, '2024-03-04', '2024-03-09', 'SHIPPED',   1690.00,   6),
    (1028, 102, '2024-03-21', '2024-03-25', 'SHIPPED',   1240.00,   5),
    (1029, 101, '2024-04-06', '2024-04-09', 'SHIPPED',   7460.00,  24),
    (1030, 109, '2024-04-23', '2024-04-28', 'SHIPPED',   5180.00,  17),
    (1031, 103, '2024-05-10', '2024-05-14', 'SHIPPED',   4025.00,  14),
    (1032, 107, '2024-05-28', '2024-06-01', 'SHIPPED',  12850.00,  41),
    (1033, 105, '2024-06-13', NULL,         'PENDING',   6900.00,  22),
    (1034, 109, '2024-06-30', '2024-07-04', 'SHIPPED',   4760.00,  16),
    (1035, 101, '2024-07-18', '2024-07-21', 'SHIPPED',   8820.00,  29),
    (1036, 104, '2024-08-02', '2024-08-07', 'SHIPPED',   2540.00,   9),
    (1037, 107, '2024-08-25', '2024-08-29', 'SHIPPED',  13100.00,  43),
    (1038, 109, '2024-09-11', '2024-09-15', 'SHIPPED',   5930.00,  19),
    (1039, 102, '2024-09-29', '2024-10-03', 'RETURNED',  1080.00,   4),
    (1040, 101, '2024-10-16', '2024-10-19', 'SHIPPED',   9640.00,  31);

-- One deliberate NULL amount, inserted separately so it is easy to see why it
-- is there. It makes COUNT(*), COUNT(AMOUNT) and SUM() give different answers.
INSERT INTO ORDERS VALUES
    (1041, 106, '2024-11-05', NULL, 'PENDING', NULL, 3);

A moving average needs a series, so let's roll those orders up to one row per month.

Query — the raw series
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START,
       COUNT(*) AS N_ORDERS, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1 ORDER BY 1;
Result23 rows · 3 columns
MONTH_STARTN_ORDERSTOTAL
2023-01-0125090.50
2023-02-0127650.00
2023-03-0127330.75
2023-04-0129010.00
2023-05-0123980.25
2023-06-01210075.50
2023-07-0127170.00
2023-08-01212110.00
2023-09-0115540.00
2023-10-0128445.00
2023-11-01211380.00
2023-12-0128980.00
2024-01-01215110.00
2024-02-0118340.00
2024-03-0122930.00
2024-04-01212640.00
2024-05-01216875.00
2024-06-01211660.00
2024-07-0118820.00
2024-08-01215640.00
2024-09-0127010.00
2024-10-0119640.00
2024-11-011NULL

Twenty-three monthly rows. Read TOTAL down the column and you can see it jump about. A quiet month, then a strong one, then a quiet one again. That is the noise a moving average exists to take off, so we can see the shape of the series underneath.

Two things about this series matter later, so let's notice them now. N_ORDERS is small and it is not the same on every row. And the last row has no TOTAL at all. It says NULL, because the single order in that month has a NULL AMOUNT.

Let's start with a trailing three-month average

AVG over ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is this month plus the two before it. That is a trailing three-month average. It is the sliding frame from Episode 54 with AVG on it instead of SUM.

Because it is a frame, the trick from Episode 54 still works. Put COUNT(*) over the same frame and the size of the window arrives as a column of its own.

Query
WITH M AS (
  SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
  FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
       AVG(TOTAL) OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MA3,
       COUNT(*)   OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ROWS_AVERAGED
FROM M
ORDER BY MONTH_START;
Result23 rows · 4 columns
MONTH_STARTTOTALMA3ROWS_AVERAGED
2023-01-015090.505090.500001
2023-02-017650.006370.250002
2023-03-017330.756690.416663
2023-04-019010.007996.916663
2023-05-013980.256773.666663
2023-06-0110075.507688.583333
2023-07-017170.007075.250003
2023-08-0112110.009785.166663
2023-09-015540.008273.333333
2023-10-018445.008698.333333
2023-11-0111380.008455.000003
2023-12-018980.009601.666663
2024-01-0115110.0011823.333333
2024-02-018340.0010810.000003
2024-03-012930.008793.333333
2024-04-0112640.007970.000003
2024-05-0116875.0010815.000003
2024-06-0111660.0013725.000003
2024-07-018820.0012451.666663
2024-08-0115640.0012040.000003
2024-09-017010.0010490.000003
2024-10-019640.0010763.333333
2024-11-01NULL8325.000003

Compare MA3 with TOTAL on the same row. MA3 moves far less. That is the whole effect, and it is the reason anyone wants it.

March is the first row whose window is full. Its MA3 is the mean of January, February and March. April’s window has moved on by one month. It has dropped January and picked up April.

There is no new syntax after this. Everything from here on is about what this grid gets wrong when the data is less tidy than it looks.

Now let's look at the rows at the start

Read ROWS_AVERAGED down the trailing three-month grid, starting at the top. January’s window holds one row, because there is no month before January for the frame to reach into. February’s holds two. March is the first row with three.

So the first two figures in that column are not three-month averages. January’s “three-month average” is January. They are not wrong. AVG divided by the rows the frame really held. But they are not the thing the column name promises, and on a chart they will read as a trend that is not there.

Rather than eyeball the top of a grid, let's count it.

Query
WITH M AS (
  SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
  FROM ORDERS GROUP BY 1
)
SELECT COUNT(*) AS MONTHS,
       COUNT_IF(N = 3) AS ROWS_WITH_A_FULL_WINDOW,
       COUNT_IF(N < 3) AS ROWS_WITH_A_PARTIAL_WINDOW
FROM (SELECT COUNT(*) OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS N
      FROM M);
Result1 row · 3 columns
MONTHSROWS_WITH_A_FULL_WINDOWROWS_WITH_A_PARTIAL_WINDOW
23212

Twenty-three months, twenty-one with a full window, two partial. Two short rows out of twenty-three hardly matters. On a short series, or with a twelve-month frame, it matters a great deal.

Or let's blank them out

We have two options and neither one is the correct one. Leave the short rows alone and know what they are, or refuse to report an average until the window is full. The second one is a CASE on the window’s own COUNT(*).

Query
WITH M AS (
  SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
  FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
       CASE WHEN COUNT(*) OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) = 3
            THEN AVG(TOTAL) OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
       END AS MA3_STRICT
FROM M
ORDER BY MONTH_START;
Result23 rows · 3 columns
MONTH_STARTTOTALMA3_STRICT
2023-01-015090.50NULL
2023-02-017650.00NULL
2023-03-017330.756690.41666
2023-04-019010.007996.91666
2023-05-013980.256773.66666
2023-06-0110075.507688.58333
2023-07-017170.007075.25000
2023-08-0112110.009785.16666
2023-09-015540.008273.33333
2023-10-018445.008698.33333
2023-11-0111380.008455.00000
2023-12-018980.009601.66666
2024-01-0115110.0011823.33333
2024-02-018340.0010810.00000
2024-03-012930.008793.33333
2024-04-0112640.007970.00000
2024-05-0116875.0010815.00000
2024-06-0111660.0013725.00000
2024-07-018820.0012451.66666
2024-08-0115640.0012040.00000
2024-09-017010.0010490.00000
2024-10-019640.0010763.33333
2024-11-01NULL8325.00000

January and February are NULL now, and MA3_STRICT is the same as MA3 from March onwards. A chart will simply start the line in March. That is honest. The three-month average really does not exist before then.

One more thing in the same grid

Now look at the last row of either grid. Its TOTAL is NULL. And yet ROWS_AVERAGED says three, and there is an average sitting beside it. The CASE version kept that figure too, because the count was satisfied.

The window was full. The data was not.

COUNT(*) counts rows. AVG skips NULLs. Those two can disagree inside one window, and here they do. That last figure is the average of two months over a window of three. It is the same COUNT(*) against COUNT(col) behaviour we saw in Episode 46. So COUNT(*) is the wrong guard if what you care about is how many values were averaged.

Now let's try a centred window instead

A trailing window is not the only shape we can ask for. ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING is one month back and one month forward. That is a centred moving average. Let's put both in one query.

Query
WITH M AS (
  SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
  FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
       AVG(TOTAL) OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)  AS TRAILING_3,
       AVG(TOTAL) OVER (ORDER BY MONTH_START ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)  AS CENTRED_3
FROM M
ORDER BY MONTH_START;
Result23 rows · 4 columns
MONTH_STARTTOTALTRAILING_3CENTRED_3
2023-01-015090.505090.500006370.25000
2023-02-017650.006370.250006690.41666
2023-03-017330.756690.416667996.91666
2023-04-019010.007996.916666773.66666
2023-05-013980.256773.666667688.58333
2023-06-0110075.507688.583337075.25000
2023-07-017170.007075.250009785.16666
2023-08-0112110.009785.166668273.33333
2023-09-015540.008273.333338698.33333
2023-10-018445.008698.333338455.00000
2023-11-0111380.008455.000009601.66666
2023-12-018980.009601.6666611823.33333
2024-01-0115110.0011823.3333310810.00000
2024-02-018340.0010810.000008793.33333
2024-03-012930.008793.333337970.00000
2024-04-0112640.007970.0000010815.00000
2024-05-0116875.0010815.0000013725.00000
2024-06-0111660.0013725.0000012451.66666
2024-07-018820.0012451.6666612040.00000
2024-08-0115640.0012040.0000010490.00000
2024-09-017010.0010490.0000010763.33333
2024-10-019640.0010763.333338325.00000
2024-11-01NULL8325.000009640.00000

The two columns hold the same figures, offset by a row. January’s CENTRED_3 is the same value as February’s TRAILING_3. That is not a coincidence. The centred window on January is January and February. The trailing window on February is also January and February. Same two rows, same average, reported against a different month.

So we have a trade-off, and it is not a matter of taste.

TrailingCentred
Frame2 PRECEDING to CURRENT ROW1 PRECEDING to 1 FOLLOWING
Usesonly the pastthe past and the future
Availablethe day the period closesonly once the next period is in
Changes afterwardsneverno, but it cannot be computed yet
Lines up with the period it is reported againstlags behind ityes
Short windows atthe startthe start and the end

A trailing average is what we put on an operational dashboard. It exists the moment the month closes and it never changes afterwards. A centred average is what we put in an analysis of a finished period, because it does not lag the series it describes.

Can the frame skip a month?

This is the one that bites everybody who does this on real data, and it is silent when it does.

ROWS BETWEEN 2 PRECEDING AND CURRENT ROW counts rows. It does not count months. A month with no orders in it does not come back as a row with a zero in it. It is simply not in the result of the GROUP BY at all. The frame then reaches across the gap to whatever row is there instead, and our three-month average quietly becomes a three-row average spanning four or five months.

Nothing in the grid tells us that happened. So let's check, rather than assume. First, how wide is the series supposed to be?

Query
SELECT COUNT(DISTINCT DATE_TRUNC('MONTH', ORDER_DATE)) AS MONTHS_WITH_ORDERS,
       MIN(ORDER_DATE) AS FIRST_ORDER,
       MAX(ORDER_DATE) AS LAST_ORDER,
       DATEDIFF('MONTH', MIN(ORDER_DATE), MAX(ORDER_DATE)) + 1 AS CALENDAR_MONTHS_SPANNED
FROM ORDERS;
Result1 row · 4 columns
MONTHS_WITH_ORDERSFIRST_ORDERLAST_ORDERCALENDAR_MONTHS_SPANNED
232023-01-122024-11-0523

The months that actually have orders and the calendar months between the first and last order are the same figure. That is the check in one row. If any month were missing, the calendar span would be the larger of the two.

Now let's name the same thing month by month. We build a calendar of every month in that span and look for the ones with nothing joined to them.

Query
WITH RECURSIVE BOUNDS AS (
  SELECT DATE_TRUNC('MONTH', MIN(ORDER_DATE)) AS FIRST_M,
         DATE_TRUNC('MONTH', MAX(ORDER_DATE)) AS LAST_M
  FROM ORDERS
),
CAL (M) AS (
  SELECT FIRST_M FROM BOUNDS
  UNION ALL
  SELECT DATEADD('MONTH', 1, M) FROM CAL WHERE M < (SELECT LAST_M FROM BOUNDS)
),
MONTHLY AS (
  SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, COUNT(*) AS N
  FROM ORDERS GROUP BY 1
)
SELECT C.M AS EMPTY_MONTH
FROM CAL C LEFT JOIN MONTHLY T ON T.MONTH_START = C.M
WHERE T.MONTH_START IS NULL
ORDER BY C.M;
Result0 rows · 1 column
EMPTY_MONTH

No rows came back, so there are no empty months. The trap does not bite on this data. That is worth saying plainly rather than implying a bug that is not there. What the two checks buy us is the right to trust the earlier grids.

Let's fix a gap with a calendar spine, and see what it changes

If a month could be missing, the shape to reach for is a calendar spine. We generate every month in the span, left join the aggregated data onto it, and COALESCE the total so an absent month becomes a row carrying zero. Then a row is a month again, and the frame means what we think it means.

Query
WITH RECURSIVE BOUNDS AS (
  SELECT DATE_TRUNC('MONTH', MIN(ORDER_DATE)) AS FIRST_M,
         DATE_TRUNC('MONTH', MAX(ORDER_DATE)) AS LAST_M
  FROM ORDERS
),
CAL (M) AS (
  SELECT FIRST_M FROM BOUNDS
  UNION ALL
  SELECT DATEADD('MONTH', 1, M) FROM CAL WHERE M < (SELECT LAST_M FROM BOUNDS)
),
MONTHLY AS (
  SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
  FROM ORDERS GROUP BY 1
),
SPINE AS (
  SELECT C.M AS MONTH_START, COALESCE(T.TOTAL, 0) AS TOTAL
  FROM CAL C LEFT JOIN MONTHLY T ON T.MONTH_START = C.M
)
SELECT MONTH_START, TOTAL,
       AVG(TOTAL) OVER (ORDER BY MONTH_START ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MA3_ON_SPINE
FROM SPINE
ORDER BY MONTH_START;
Result23 rows · 3 columns
MONTH_STARTTOTALMA3_ON_SPINE
2023-01-015090.505090.50000
2023-02-017650.006370.25000
2023-03-017330.756690.41666
2023-04-019010.007996.91666
2023-05-013980.256773.66666
2023-06-0110075.507688.58333
2023-07-017170.007075.25000
2023-08-0112110.009785.16666
2023-09-015540.008273.33333
2023-10-018445.008698.33333
2023-11-0111380.008455.00000
2023-12-018980.009601.66666
2024-01-0115110.0011823.33333
2024-02-018340.0010810.00000
2024-03-012930.008793.33333
2024-04-0112640.007970.00000
2024-05-0116875.0010815.00000
2024-06-0111660.0013725.00000
2024-07-018820.0012451.66666
2024-08-0115640.0012040.00000
2024-09-017010.0010490.00000
2024-10-019640.0010763.33333
2024-11-010.005550.00000

On this data the spine adds no rows, because there were no gaps to fill. But look at the last row, and compare it with the last row of the trailing three-month grid.

The fix changes the answer

COALESCE caught the last month’s NULL total as well as any missing month. So that row’s TOTAL is now zero instead of NULL, and its moving average drops. The window is now averaging three months, one of which is zero, instead of averaging the two that had values. That is a modelling decision, not a formatting one. Treating a month with no data as a month that sold nothing drags the average down. Do it on purpose, or do not do it.

Those are two different claims about the world. That month sold nothing and we do not know what that month sold. A zero says the first one. A NULL says the second one. The query cannot tell which is true, so we have to.

Now let's measure the window in days instead of rows

Every frame so far has counted rows, which is why the missing-month problem existed at all. RANGE, from Episode 55, takes an offset instead. With a date as the ordering column that offset can be an INTERVAL. RANGE BETWEEN INTERVAL '90 DAYS' PRECEDING AND CURRENT ROW is a rolling window really measured in days, and gaps in the data cannot distort it.

No monthly grouping this time. This one runs over the orders themselves. We put the left edge of the window on screen as MIN(ORDER_DATE) over the same frame, so we can watch it move. The query carries LIMIT 14, so the grid is the start of the series rather than all of it.

Query
SELECT ORDER_DATE, AMOUNT,
       SUM(AMOUNT)   OVER (ORDER BY ORDER_DATE
                           RANGE BETWEEN INTERVAL '90 DAYS' PRECEDING AND CURRENT ROW) AS TOTAL_LAST_90D,
       COUNT(*)      OVER (ORDER BY ORDER_DATE
                           RANGE BETWEEN INTERVAL '90 DAYS' PRECEDING AND CURRENT ROW) AS ORDERS_LAST_90D,
       MIN(ORDER_DATE) OVER (ORDER BY ORDER_DATE
                           RANGE BETWEEN INTERVAL '90 DAYS' PRECEDING AND CURRENT ROW) AS WINDOW_FROM
FROM ORDERS
ORDER BY ORDER_DATE
LIMIT 14;
Result14 rows · 5 columns
ORDER_DATEAMOUNTTOTAL_LAST_90DORDERS_LAST_90DWINDOW_FROM
2023-01-124200.004200.0012023-01-12
2023-01-28890.505090.5022023-01-12
2023-02-146150.0011240.5032023-01-12
2023-02-271500.0012740.5042023-01-12
2023-03-092310.7515051.2552023-01-12
2023-03-225020.0020071.2562023-01-12
2023-04-057890.0027961.2572023-01-12
2023-04-191120.0024881.2572023-01-28
2023-05-023340.2527331.0072023-02-14
2023-05-21640.0021821.0072023-02-27
2023-06-088100.0026110.2562023-03-22
2023-06-251975.5023065.7562023-04-05
2023-07-116420.0021595.7562023-04-19
2023-07-29750.0021225.7562023-05-02

WINDOW_FROM is the column to watch. It holds at the first order date for the first seven rows, because nothing has fallen out of the window yet. Then it moves on. By the eighth row the first order is 97 days back, and 97 days is outside a 90-day window. We can watch the left edge slide.

ORDERS_LAST_90D is the other column to read. It climbs while the window is filling, holds at seven for a stretch, then settles back to six as orders leave the window faster than they arrive. That column is the point of a time-based window. The count is whatever the dates say it is, and it is allowed to go down. A ROWS frame can never do that. 2 PRECEDING is always two rows, however far apart in time they happen to be.

Let's do one rolling average per customer

Last of all, the shape that turns up in real work more than any other on this page. A rolling average worked out separately for each customer. We add PARTITION BY CUSTOMER_ID, order by date, and keep the same trailing frame.

Query
SELECT CUSTOMER_ID, ORDER_ID, ORDER_DATE, AMOUNT,
       AVG(AMOUNT) OVER (PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE, ORDER_ID
                         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS AVG_LAST_3,
       COUNT(*)    OVER (PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE, ORDER_ID
                         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ROWS_AVERAGED
FROM ORDERS
ORDER BY CUSTOMER_ID, ORDER_DATE, ORDER_ID
LIMIT 14;
Result14 rows · 6 columns · scroll →
CUSTOMER_IDORDER_IDORDER_DATEAMOUNTAVG_LAST_3ROWS_AVERAGED
10110012023-01-124200.004200.000001
10110032023-02-146150.005175.000002
10110062023-03-225020.005123.333333
10110112023-06-088100.006423.333333
10110172023-09-165540.006220.000003
10110232023-12-276730.006790.000003
10110292024-04-067460.006576.666663
10110352024-07-188820.007670.000003
10110402024-10-169640.008640.000003
10210022023-01-28890.50890.500001
10210082023-04-191120.001005.250002
10210142023-07-29750.00920.166663
10210212023-11-24980.00950.000003
10210282024-03-211240.00990.000003

The frame restarts in every partition. ROWS_AVERAGED goes back to one at each new customer, and AVG_LAST_3 never mixes two customers’ orders. This grid carries LIMIT 14 as well. It holds the whole of customer 101’s history, because the count restarts and the grid moves on to customer 102.

Notice that the short-window problem now arrives once per customer rather than once per query. A customer with one order has a one-row window, and AVG_LAST_3 on that row is just their order amount. On a customer table with a long tail of one-order customers, most of our “rolling average” is not rolling at all. That is exactly the kind of thing COUNT(*) over the same frame is for.

Key points

  • A moving average is a window frame and nothing else: AVG over ROWS BETWEEN n PRECEDING AND CURRENT ROW. There is no moving-average function to learn.
  • Put COUNT(*) over the same frame every time. It is the only thing that tells you how big the window really was on each row.
  • The first rows of any trailing window are short, so their averages are over fewer periods than the column name claims. Keep them knowingly, or blank them with a CASE on the window’s own count.
  • COUNT(*) counts rows and AVG skips NULLs, so a full window can still average fewer values than it holds rows.
  • Trailing uses only the past, so it is final the moment the period closes. Centred is smoother and lines up with its own period, but it cannot be computed until the next period exists.
  • ROWS counts rows, not months. A period with no data is not a row, and the frame will silently reach across the gap.
  • Check for gaps rather than assuming them away. Compare the periods that have data with the calendar periods spanned, and list the empty ones.
  • A calendar spine plus COALESCE makes every period a row, and it changes the answer, because it turns “we do not know” into “zero”. That is a modelling decision.
  • For a window that really is a length of time, use RANGE with an INTERVAL offset and let the dates decide which rows are in it.
Next in this series

In the next post we will look at RATIO_TO_REPORT, WIDTH_BUCKET and CONDITIONAL_TRUE_EVENT. Each row as a share of its group, values bucketed into bands, and a counter that goes up every time a condition turns true.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The ORDERS data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series. Frame behaviour follows the Snowflake window functions documentation and the window frame syntax reference.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.