28/34
Part 6 of 6 · Follow-upsLearn
A worked example
Put the pieces together on the orders table. For each order, find the user's order number, the days since their previous order, their running spend, and the store's orders in the 7 days ending on that date:
SELECT user_id, ordered_on, amount,
ROW_NUMBER() OVER u AS nth,
CAST(julianday(ordered_on) - julianday(LAG(ordered_on) OVER u)
AS INTEGER) AS gap_days,
SUM(amount) OVER u AS running_spend,
COUNT(*) OVER (ORDER BY julianday(ordered_on)
RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS store_7d
FROM orders
WINDOW u AS (PARTITION BY user_id ORDER BY ordered_on, order_id)
ORDER BY user_id, nth;
| user_id | ordered_on | amount | nth | gap_days | running_spend | store_7d |
|---|---|---|---|---|---|---|
| 1 | 2026-03-01 | 30 | 1 | NULL | 30 | 2 |
| 1 | 2026-03-02 | 45 | 2 | 1 | 75 | 3 |
| 1 | 2026-03-03 | 45 | 3 | 1 | 120 | 5 |
| 2 | 2026-03-01 | 20 | 1 | NULL | 20 | 2 |
| 2 | 2026-03-09 | 35 | 2 | 8 | 55 | 3 |
| 3 | 2026-03-03 | 25 | 1 | NULL | 25 | 5 |
| 4 | 2026-03-10 | 50 | 1 | NULL | 50 | 2 |
Check one row by hand, user 2's order on March 9:
| column | value | why |
|---|---|---|
nth | 2 | user 2's orders by date are March 1, then March 9 |
gap_days | 8 | March 1 to March 9 |
running_spend | 55 | 20 + 35, and u sorts on a unique key, so the default frame stops at this order |
store_7d | 3 | the window runs March 3 to 9: orders 3 and 4 on March 3, order 5 on March 9 |
Two windows with different partitions in one SELECT are fine, since each function uses its own OVER. store_7d has no PARTITION BY, so it counts the whole store. The two March 3 orders are peers, and they share a count of 5.