Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.
Seven-day query
WITH RECURSIVE calendar(day) AS (
SELECT '2024-02-26'
UNION ALL
SELECT date(day, '+1 day')
FROM calendar
WHERE day < '2024-03-05'
), daily AS (
SELECT store, day, SUM(amount_cents) AS total_cents
FROM sales_average_demo
GROUP BY store, day
), series AS (
SELECT t.store, c.day,
COALESCE(d.total_cents, 0) AS total_cents
FROM stores_average_demo AS t
CROSS JOIN calendar AS c
LEFT JOIN daily AS d
ON d.store = t.store AND d.day = c.day
), windows AS (
SELECT store, day, total_cents,
COUNT(*) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS days_in_window,
ROUND(AVG(total_cents * 1.0) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2) AS partial_average
FROM series
)
SELECT store, day, total_cents, days_in_window,
CASE WHEN days_in_window = 7
THEN partial_average END AS average_7_days_cents
FROM windows
ORDER BY store, day;Set up the example data
The North shop makes two sales on 26 February and none on 27 February or 1 March. South has sales on three days. The period runs from 26 February to 5 March 2024: it includes 29 February and spans nine days, even though neither shop has sales on all nine.
We store amounts in cents, and the averages are shown in cents too: 1071.43 is roughly 10.71 currency units per day. The shops table is independent of their sales, so a shop still appears even when it has no transactions.
CREATE TABLE stores_average_demo (
store TEXT PRIMARY KEY
);
CREATE TABLE sales_average_demo (
id INTEGER PRIMARY KEY,
store TEXT NOT NULL,
day TEXT NOT NULL,
amount_cents INTEGER NOT NULL
);
INSERT INTO stores_average_demo VALUES ('North'), ('South');
INSERT INTO sales_average_demo VALUES
(1, 'North', '2024-02-26', 1000),
(2, 'North', '2024-02-26', 500),
(3, 'North', '2024-02-28', 900),
(4, 'North', '2024-02-29', 1200),
(5, 'North', '2024-03-02', 1800),
(6, 'North', '2024-03-03', 2100),
(7, 'North', '2024-03-04', 2400),
(8, 'North', '2024-03-05', 3000),
(9, 'South', '2024-02-26', 700),
(10,'South', '2024-02-28', 1400),
(11,'South', '2024-03-02', 2100);Download data and queries (.sql)
The file is ready for an empty SQLite database and contains the same examples as this guide. Run it once on a test connection that supports window functions. The course's teaching engine does not support all of these constructs, so use SQLite to reproduce the full case.
With an unbroken series, the six previous rows plus the current one are seven consecutive days. Counting the rows in the same window lets you tell a complete average apart from the partial averages at the start.
First complete averages: result for the last three days
| Store | Day | Daily total | Days | 7-day average |
|---|---|---|---|---|
| North | 2024-03-03 | 2100 | 7 | 1071.43 |
| North | 2024-03-04 | 2400 | 7 | 1200 |
| North | 2024-03-05 | 3000 | 7 | 1628.57 |
| South | 2024-03-03 | 0 | 7 | 600 |
| South | 2024-03-04 | 0 | 7 | 500 |
| South | 2024-03-05 | 0 | 7 | 500 |
The full result has eighteen rows, nine per shop. For the first six days of each shop, average_7_days_cents is NULL. That does not mean there were no sales: the loaded history does not yet contain seven days. You could show partial averages, but they should have a name and a day count that make that clear.
For North, the 5 March window covers 28 and 29 February and 1, 2, 3, 4 and 5 March. The sum is 11400, and 11400 / 7 gives 1628.57 after rounding. South's transactions are not included because the window is partitioned by shop.
How it works
First we add up the transactions per shop and day. Then we cross the list of shops with a calendar of consecutive dates and attach the daily total. Here COALESCE turns a date with no transactions into zero because we know the records are complete.
WITH RECURSIVE calendar(day) AS (
SELECT '2024-02-26'
UNION ALL
SELECT date(day, '+1 day')
FROM calendar
WHERE day < '2024-03-05'
), daily AS (
SELECT store, day, SUM(amount_cents) AS total_cents
FROM sales_average_demo
GROUP BY store, day
), series AS (
SELECT t.store, c.day,
COALESCE(d.total_cents, 0) AS total_cents
FROM stores_average_demo AS t
CROSS JOIN calendar AS c
LEFT JOIN daily AS d
ON d.store = t.store AND d.day = c.day
)
SELECT store, day, total_cents
FROM series
ORDER BY store, day;Daily series for North, in cents
| Day | Daily total |
|---|---|
| 2024-02-26 | 1500 |
| 2024-02-27 | 0 |
| 2024-02-28 | 900 |
| 2024-02-29 | 1200 |
| 2024-03-01 | 0 |
| 2024-03-02 | 1800 |
| 2024-03-03 | 2100 |
| 2024-03-04 | 2400 |
| 2024-03-05 | 3000 |
The calendar produces a single date per day and the aggregation returns a single row per shop and date, which is why the JOIN does not multiply the amounts. Use normalised dates and the business time zone before grouping timestamps; cutting a date string without resolving its time zone can assign sales to the wrong day.
Cases that change the result
The mistake: averaging seven rows and calling it seven days
Grouping transactions by day is necessary, but it still does not fill in the dates with no sales. This query averages up to seven days that do have transactions. It does not calculate the daily average over a calendar week.
WITH daily AS (
SELECT store, day, SUM(amount_cents) AS total_cents
FROM sales_average_demo
GROUP BY store, day
)
SELECT store, day,
COUNT(*) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rows_in_window,
ROUND(AVG(total_cents * 1.0) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2) AS average_days_with_sales
FROM daily
WHERE store = 'North'
ORDER BY day;On 5 March it returns 1842.86: it has taken North's seven dates with sales, going back to 26 February, a span of nine days. On 3 March it has only five rows and averages 1500. If you presented both figures as seven-day averages, you would be changing the denominator without saying so.
The reference on ROWS BETWEEN explains how to count positions in a window. To turn positions into days, the data model must guarantee one row per date.
Zero sales, unknown data and a closed shop
These are three different situations. Zero sales is a known observation; unknown data means you cannot be sure how much was sold; a closed shop depends on the agreed denominator. An average per calendar day may count closures as zero. An average per trading day needs an opening calendar and a different window definition.
AVG skips NULL. This small example shows why filling in a zero can change the answer:
WITH sample(amount_cents) AS (
VALUES (0), (NULL), (2100)
)
SELECT COUNT(*) AS days,
COUNT(amount_cents) AS days_with_data,
AVG(amount_cents) AS average_known,
AVG(COALESCE(amount_cents, 0)) AS average_imputing_zero
FROM sample;An unknown day changes the denominator
| Days | Known values | Average of known values | Average with zero filled in |
|---|---|---|---|
| 3 | 2 | 1050 | 700 |
If the system can have days still waiting to load, add their status to the calendar and require seven known amounts with COUNT(total_cents). Do not treat COUNT(*) as a guarantee of complete data when the column allows NULL. The main query can use it because its rules already define every gap as a known zero.
Filtering the visible dates after the window
A dashboard that starts on 3 March needs earlier data to calculate that first point. For a seven-day window, load from 26 February, calculate the average and then filter to the visible period. If you filter before AVG OVER, you start from a truncated history.
WITH RECURSIVE calendar(day) AS (
SELECT '2024-02-26'
UNION ALL
SELECT date(day, '+1 day')
FROM calendar
WHERE day < '2024-03-05'
), daily AS (
SELECT store, day, SUM(amount_cents) AS total_cents
FROM sales_average_demo
GROUP BY store, day
), series AS (
SELECT t.store, c.day,
COALESCE(d.total_cents, 0) AS total_cents
FROM stores_average_demo AS t
CROSS JOIN calendar AS c
LEFT JOIN daily AS d
ON d.store = t.store AND d.day = c.day
), windows AS (
SELECT store, day, total_cents,
COUNT(*) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS days_in_window,
ROUND(AVG(total_cents * 1.0) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2) AS partial_average
FROM series
)
SELECT store, day, total_cents, days_in_window,
CASE WHEN days_in_window = 7
THEN partial_average END AS average_7_days_cents
FROM windows
WHERE day >= '2024-03-03' AND day < '2024-03-06'
ORDER BY store, day;This query keeps the six rows before the first visible day and returns exactly the six rows of the previous table. The chosen interval generates only the dates this case needs. In production, use a maintained calendar table or generate the shortest span that covers both history and display; do not cross every entity with decades of dates for no reason.
Adapting it per engine and choosing between ROWS and RANGE
The AVG OVER calculation over a regular daily series carries over to PostgreSQL, MySQL 8.0 or later and SQL Server 2012 or later. What changes is how the calendar is built. In SQL Server, converting the amount to a decimal type before AVG keeps the decimals; do not trust the average of an integer expression.
Preparing the daily series on other engines
| Engine | Calendar and dates |
|---|---|
| SQLite | Recursive CTE with date(day, '+1 day') |
| PostgreSQL | A persistent calendar table or generate_series; cast the result to date |
| MySQL 8.0+ | A persistent calendar table or a recursive CTE with DATE_ADD and a suitable recursion limit |
| SQL Server | A persistent calendar table or a CTE with DATEADD and suitable recursion settings |
A date-based RANGE can select observations by date distance on engines that support that frame. It does not create missing days or change the denominator to seven. For this average of sales per calendar day, the filled-in series makes it clear which days count and avoids depending on an engine-specific date variant.
The scripts on this page were run in SQLite. The adaptations for other engines are based on their official documentation; they have not been run here against those servers.
Checking a different window
WITH RECURSIVE calendar(day) AS (
SELECT '2024-02-26'
UNION ALL
SELECT date(day, '+1 day')
FROM calendar
WHERE day < '2024-03-05'
), daily AS (
SELECT store, day, SUM(amount_cents) AS total_cents
FROM sales_average_demo
GROUP BY store, day
), series AS (
SELECT t.store, c.day,
COALESCE(d.total_cents, 0) AS total_cents
FROM stores_average_demo AS t
CROSS JOIN calendar AS c
LEFT JOIN daily AS d
ON d.store = t.store AND d.day = c.day
), windows AS (
SELECT store, day, total_cents,
COUNT(*) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS days_in_window,
ROUND(AVG(total_cents * 1.0) OVER (
PARTITION BY store ORDER BY day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
), 2) AS partial_average
FROM series
)
SELECT store, day, total_cents, days_in_window,
CASE WHEN days_in_window = 3
THEN partial_average END AS average_3_days_cents
FROM windows
WHERE store = 'North' AND day >= '2024-03-03' AND day < '2024-03-06'
ORDER BY store, day;Three-day moving average, in cents
| Day | Daily total | 3-day average |
|---|---|---|
| 2024-03-03 | 2100 | 1300 |
| 2024-03-04 | 2400 | 2100 |
| 2024-03-05 | 3000 | 2500 |
On 3 March it averages 0, 1800 and 2100. On 5 March it averages 2100, 2400 and 3000. The shorter window reacts faster to recent sales; that does not make it a better measure for every purpose. Choose the length based on the question the report answers.