In SQLite, a 7-day window by date is RANGE 6 PRECEDING over a day number
The practice's third query wants, for every date with bookings, the bookings in the 7 days ending on that date. It takes two steps:
- Count per date, so each date is one row.
- Sum those counts over a RANGE frame on the day number.
WITH daily AS (
SELECT ordered_on, COUNT(*) AS n
FROM orders
GROUP BY ordered_on
)
SELECT ordered_on,
SUM(n) OVER (ORDER BY julianday(ordered_on)
RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS orders_7d,
SUM(n) OVER (ORDER BY julianday(ordered_on)
RANGE BETWEEN 7 PRECEDING AND CURRENT ROW) AS orders_8d
FROM daily
ORDER BY ordered_on;
| ordered_on | orders_7d | orders_8d |
|---|---|---|
| 2026-03-01 | 2 | 2 |
| 2026-03-02 | 3 | 3 |
| 2026-03-03 | 5 | 5 |
| 2026-03-09 | 3 | 4 |
| 2026-03-10 | 2 | 4 |
Count the days for March 9:
Orders: 1 on March 2, 2 on March 3 and 1 on March 9, at the dashed lines.
The 7 days ending March 9 are March 3 through March 9: the date itself and the 6 before it. That's 6 PRECEDING.
For March 9, 7 PRECEDING starts on March 2, which makes eight days. It counts 4 on both March 9 and March 10, where the right answers are 3 and 2.
The same off-by-one hides in the last 30 days, which is 29 PRECEDING, and in every inclusive range. The number of days is the end minus the start, plus one.
In the editor, write WINDOW_START: the first day of each date's 7-day window, so you can see the frame's reach.