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_idordered_onamountnthgap_daysrunning_spendstore_7d
12026-03-01301NULL302
12026-03-024521753
12026-03-0345311205
22026-03-01201NULL202
22026-03-093528553
32026-03-03251NULL255
42026-03-10501NULL502

Check one row by hand, user 2's order on March 9:

columnvaluewhy
nth2user 2's orders by date are March 1, then March 9
gap_days8March 1 to March 9
running_spend5520 + 35, and u sorts on a unique key, so the default frame stops at this order
store_7d3the 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.