Running totals and moving averages
Running totals accumulate values; moving averages summarize a limited neighborhood around each row.
Understand the idea
Each row is a fictional sale event. Dates use one calendar and amounts use one currency. Tied dates, tied amounts, an unknown amount and a known zero make the edge cases visible. Every SQL block includes these rows.
| Concept | What it means |
|---|---|
| UNBOUNDED PRECEDING | Start at the beginning of the partition. |
| CURRENT ROW | End at the current frame position. |
| Two preceding rows | Three row positions including the current one, not necessarily three calendar days. |
A concrete example
A has amounts 100, 50, 50 and NULL. SUM ignores the NULL, so the cumulative total ends at 200.
Remember: Decide whether the window means records or elapsed time; gaps in dates make them different.
Explain it step by step · full theory
The seven input events
Each row is a fictional sale event. Dates use one calendar and amounts use one currency. Tied dates, tied amounts, an unknown amount and a known zero make the edge cases visible. Every SQL block includes these rows.
| EVENT_ID | CUSTOMER | EVENT_DATE | AMOUNT |
|---|---|---|---|
| 1 | A | 2025-01-01 | 100 |
| 2 | A | 2025-01-02 | 50 |
| 3 | A | 2025-01-02 | 50 |
| 4 | A | 2025-01-05 | NULL |
| 5 | B | 2025-01-01 | 80 |
| 6 | B | 2025-01-03 | 20 |
| 7 | B | 2025-01-04 | 0 |
A running total grows with the sequence
A running total adds the values encountered so far. For A’s events, we start at 100, then add 50 to get 150, then another 50 to get 200. The final NULL leaves the known-amount sum at 200.
Partition by customer so B starts its own total. Order by event date and ID to define the sequence. Use a cumulative ROWS frame to show the sum advancing one event at a time.
A moving average looks at a smaller neighborhood
AVG with ROWS BETWEEN 1 PRECEDING AND CURRENT ROW uses the previous position and the current position. For A’s event 2, that is 100 and 50, so the average is 75. For event 3, it is 50 and 50, so the average is 50.
At the first event, there is no previous position. The frame contains only the current event. At event 4, the frame contains 50 and NULL; AVG ignores the NULL, so the average is 50, not 25.
Count the observations too
A “two-row average” does not guarantee two known values. Use COUNT(amount) over the same frame when the number of numeric observations matters. You can choose to hide or flag an average with insufficient observations.
Do not replace unknown values with zero merely to force a denominator of two. That changes the metric from averaging known observations to an imputed-value policy.
Calendar intervals ask another question
A moving date RANGE can cover the current date and an earlier interval. With a DATE order and a two-day preceding boundary, January 5 looks back to January 3. A’s January 2 events are outside that frame.
If the only included amount is NULL, SUM has no known values to add and returns NULL. A calendar frame also does not generate missing days. To report an output for every date, a separate calendar dataset and an explicit missing-day policy are needed.
Words used in this lesson
- Running total
- A sum accumulated through an ordered sequence.
- Moving average
- An average over a changing subset of nearby records or values.
- Observation count
- The number of usable values contributing to a metric.
See how it works
Choose a step to explore the idea at your own pace.
Open the interactive explanation
Running totals and moving averages
Start
A’s first frame contains just 100. Both the running sum and known-value average are 100.
Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.
Read the complete diagram explanation
- Start
A’s first frame contains just 100. Both the running sum and known-value average are 100.
- Advance
At event 2, the two-row average uses 100 and 50.
- Slide
At event 3, event 1 leaves the two-row frame.
- Missing
At event 4, the frame contains one known 50 and one unknown amount.
Try the SQL or command
Read → predict → run in your learning environment → compare. You can also learn by reading without an account.
New to SQL? Where to run it and how to read it
A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.
- No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
- For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
- Read the entire example, including comments beginning with
--. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor. - Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
- SELECT / FROM
- Choose the values to return / identify their input.
- VALUES / COLUMN1
- VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
- AS / WITH
- AS gives a result a readable name. WITH names a temporary query step within one statement.
- NULL / ::
- NULL means missing or unknown. The :: notation converts a value to a named data type.
- Session
- One connection and its settings. Keep related transaction steps in the same session.
- Database.schema.table
- A full address for stored data. It is separate from the warehouse that processes queries.
Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →
Help with common practice errors
- No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
- Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
- Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
- Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.
Before running this lesson
Seven fictional events are included in each SQL block below. Run each block independently in an authorized learning session with a warehouse; no stored SALES table is required. Results are illustrative.
Compare cumulative and two-event calculations
WITH sales AS (
SELECT column1::NUMBER AS event_id,
column2::VARCHAR AS customer,
TO_DATE(column3::VARCHAR, 'YYYY-MM-DD') AS event_date,
column4::NUMBER(12,2) AS amount
FROM VALUES
(1, 'A', '2025-01-01', 100),
(2, 'A', '2025-01-02', 50),
(3, 'A', '2025-01-02', 50),
(4, 'A', '2025-01-05', NULL),
(5, 'B', '2025-01-01', 80),
(6, 'B', '2025-01-03', 20),
(7, 'B', '2025-01-04', 0)
)
SELECT event_id, customer,
SUM(amount) OVER (PARTITION BY customer ORDER BY event_date, event_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
AVG(amount) OVER (PARTITION BY customer ORDER BY event_date, event_id
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS two_event_average
FROM sales
ORDER BY customer, event_date, event_id;What to expect and why
Each customer starts independently. AVG uses only known amounts in the two-position frame. Output numeric scale may vary by client.
| EVENT_ID | CUSTOMER | RUNNING_TOTAL | TWO_EVENT_AVERAGE |
|---|---|---|---|
| 1 | A | 100 | 100 |
| 2 | A | 150 | 75 |
| 3 | A | 200 | 50 |
| 4 | A | 200 | 50 |
| 5 | B | 80 | 80 |
| 6 | B | 100 | 50 |
| 7 | B | 100 | 10 |
Use a date interval instead of row positions
WITH sales AS (
SELECT column1::NUMBER AS event_id,
column2::VARCHAR AS customer,
TO_DATE(column3::VARCHAR, 'YYYY-MM-DD') AS event_date,
column4::NUMBER(12,2) AS amount
FROM VALUES
(1, 'A', '2025-01-01', 100),
(2, 'A', '2025-01-02', 50),
(3, 'A', '2025-01-02', 50),
(4, 'A', '2025-01-05', NULL),
(5, 'B', '2025-01-01', 80),
(6, 'B', '2025-01-03', 20),
(7, 'B', '2025-01-04', 0)
)
SELECT event_id,
SUM(amount) OVER (ORDER BY event_date
RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW) AS interval_total
FROM sales
WHERE customer = 'A'
ORDER BY event_date, event_id;What to expect and why
The interval uses date values. Both January 2 peers are included together. At January 5, the frame starts January 3; it contains only the unknown January 5 amount, so the sum is NULL.
| EVENT_ID | INTERVAL_TOTAL |
|---|---|
| 1 | 100 |
| 2 | 200 |
| 3 | 200 |
| 4 | NULL |
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
For B’s event 7, calculate the two-event average by hand.
Compare your reasoning
The frame contains event 6 with 20 and event 7 with 0. Both are known, so (20 + 0) / 2 = 10.
Official sources and curriculum
Module 04 · See module scope