The situation
Store managers get a rolling 7-day revenue number every morning. An AI assistant wrote the job in the answer cell. It was tested on the flagship store, which is open every day, and every number was right.
The manager of a store that opens only at weekends then reported that her "7-day" revenue was larger than everything the store had sold in the last three weeks.
Find the bug and fix it.
Input tables
daily_sales
One row per store per day on which the store sold something. A day the store was closed has no row.
| Column | Type | Description |
|---|---|---|
store_id |
BIGINT | The store. |
sale_date |
DATE | The day. Unique per store. |
revenue |
DECIMAL(10,2) | The store's revenue that day. Never NULL. |
Requirement
Return every row of daily_sales with the store's rolling 7-day revenue.
rolling_7d_revenueis the sum of the store'srevenueover the 7 calendar days ending onsale_date: fromsale_dateminus 6 days up to and includingsale_date.- A day without a row adds nothing. It still counts as one of the 7 days.
- No rows are added for the missing days.
Example: a store sold on 1 April, 2 April and 10 April. For 10 April the window is 4 April to 10 April, so the rolling revenue is the revenue of 10 April alone.
Expected output
One row per row of daily_sales.
| Column | Type | Description |
|---|---|---|
store_id |
BIGINT | |
sale_date |
DATE | |
revenue |
DECIMAL(10,2) | |
rolling_7d_revenue |
DECIMAL(14,2) | Revenue of the 7 calendar days ending on sale_date. |
The AI-written code
from pyspark.sql import Window from pyspark.sql import functions as F def solve(spark): """Rolling 7-day revenue per store.""" sales = spark.table("daily_sales") # Window over the current day and the six days before it last_7_days = ( Window.partitionBy("store_id") .orderBy("sale_date") .rowsBetween(-6, 0) ) result = sales.select( "store_id", "sale_date", "revenue", F.sum("revenue").over(last_7_days).cast("decimal(14,2)").alias("rolling_7d_revenue"), ) return result
Explanation
Show explanationGives the answer away. Try the problem first.
The bug
last_7_days = (
Window.partitionBy("store_id")
.orderBy("sale_date")
.rowsBetween(-6, 0)
)
rowsBetween(-6, 0) means "this row and the six rows before it". It counts
rows. It never looks at the dates in them. The comment above it says "the
current day and the six days before it", and that is only the same thing if there
is exactly one row for every calendar day.
daily_sales has a row only for days with sales. For a store that was closed on
some days, six rows back is further than six days back.
Store 8 opens at weekends only:
| sale_date | revenue | Correct 7-day revenue | The buggy job |
|---|---|---|---|
| 5 April | 15,024.00 | 15,024.00 | 15,024.00 |
| 6 April | 31,292.50 | 46,316.50 | 46,316.50 |
| 12 April | 25,546.00 | 56,838.50 | 71,862.50 |
| 13 April | 15,242.00 | 40,788.00 | 87,104.50 |
| 19 April | 33,507.50 | 48,749.50 | 120,612.00 |
| 20 April | 24,994.00 | 58,501.50 | 145,606.00 |
| 26 April | 22,867.50 | 47,861.50 | 168,473.50 |
| 27 April | 31,828.00 | 54,695.50 | 185,277.50 |
By 27 April the "7-day" number is the sum of seven rows that reach back to 6 April, three weeks earlier.
Wrong rows per store, out of 268 rows in total:
| Store | Rows | Wrong |
|---|---|---|
| 1, open every day | 45 | 0 |
| 2 to 6, closed on Sundays and a few other days | 176 | 148 |
| 7, shut for ten days | 35 | 6 |
| 8, weekends only | 12 | 10 |
Why it got through: it was tested on store 1. With no missing days, seven rows and seven days are the same and every number is right. Store 7 is nearly right as well: only the six rows after its ten-day closure are wrong.
The fix
Use a range frame. A range frame is defined by the value of the orderBy
expression, not by row positions: "all rows whose value is between the current
value minus 6 and the current value".
last_7_days = (
Window.partitionBy("store_id")
.orderBy(F.unix_date("sale_date"))
.rangeBetween(-6, 0)
)
F.unix_date turns the date into a day number (days since 1970-01-01), so that
"minus 6" means six days. A missing day simply has no row in the range.
In SQL the frame can be written on the date itself:
SUM(revenue) OVER (
PARTITION BY store_id
ORDER BY sale_date
RANGE BETWEEN INTERVAL 6 DAYS PRECEDING AND CURRENT ROW
)
Common wrong answers
orderBy("sale_date").rangeBetween(-6, 0). The natural first fix, and Spark
rejects it:
[DATATYPE_MISMATCH.RANGE_FRAME_INVALID_TYPE] ... The data type "DATE" used in the
order specification does not support the data type "BIGINT" which is used in the
range frame.
PySpark sends the frame bounds as 64-bit integers, and a DATE cannot be offset by
one. Order by a number instead: F.unix_date("sale_date"), or
F.datediff("sale_date", F.lit("2025-01-01")).
rangeBetween(-7, 0). Seven days back plus today is eight days. 201 of the 268
rows are wrong. The window is inclusive at both ends, so seven days is -6.
Dropping partitionBy("store_id"). Sums the revenue of all stores in the date
range. Every row is wrong.
Leaving out the cast. sum of a DECIMAL(10,2) is a DECIMAL(20,2). The
values are right and the check reports the type.
Other correct ways
Order by seconds. orderBy(F.unix_timestamp(F.col("sale_date").cast("timestamp")))
with rangeBetween(-6 * 86400, 0). This is the form you need when the column is a
timestamp and the window is "the last 24 hours".
Fill in the missing days first. Build one row per store and calendar day, with
NULL revenue on closed days, and then rowsBetween(-6, 0) is correct, because now
seven rows really are seven days. Remove the filler rows at the end. More steps, and
often what the report needs anyway: a chart of rolling revenue should usually show
the closed days too.
A self-join on b.sale_date BETWEEN DATE_SUB(a.sale_date, 6) AND a.sale_date. Correct,
and much more work for the engine than a window.
How to choose between rows and range
- Rows when you mean a number of records: the last 3 orders, the previous reading.
- Range when you mean a distance in the ordering value: the last 7 days, the last 30 minutes, within 100 rupees.
A rolling time window is a distance. Reach for rowsBetween only when you have made
sure, in the same job, that there is one row per time step.
Edge cases in the data
| Case | Where | What it shows |
|---|---|---|
| No missing days | store 1 | Rows and range agree; the bug is invisible. |
| Closed on Sundays, plus a few random days | stores 2 to 6 | Most rows are wrong: seven rows reach back eight days or more. |
| A gap of ten days | store 7 | The first row after the gap must equal that day's revenue alone. |
| Open two days a week | store 8 | Seven rows span more than three weeks. |
| The first rows of every store | all | Fewer than seven days of history: the sum of what there is. |