20/34
Part 4 of 6 · FramesLearn and do

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:

  1. Count per date, so each date is one row.
  2. 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_onorders_7dorders_8d
2026-03-0122
2026-03-0233
2026-03-0355
2026-03-0934
2026-03-1024

Count the days for March 9:

The frame for March 9, over the daily counts
6 PRECEDING 7 days, 3 orders
7 PRECEDING 8 days, 4 orders
23456789
day of March

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.