CODE WORKSPACE

Days between buyer orders

For each order, return buyer_id, order_id, created_at, previous_order_at (the buyer’s previous order time), and days_since_previous. Order by buyer_id, created_at.

LAG(created_at) per buyer ordered by created_at, then subtract julianday values for the gap.

Sample input

ordersEach buyer's orders, ordered by time; LAG looks one row back per buyer.
order_idbuyer_idcreated_at
100112026-01-12 08:40:00
100412026-01-15 14:20:00
100912026-01-28 18:00:00
100522026-01-18 09:05:00
101122026-02-02 09:00:00

Expected output

Expected outputFirst 5 of 12 rows. The first order per buyer has a NULL previous time (and NULL gap).
buyer_idorder_idcreated_atprevious_order_atdays_since_previous
110012026-01-12 08:40:00nullnull
110042026-01-15 14:20:002026-01-12 08:40:003
110092026-01-28 18:00:002026-01-15 14:20:0013
210052026-01-18 09:05:00nullnull
210112026-02-02 09:00:002026-01-18 09:05:0014

Constraints

Use LAG(created_at) OVER (PARTITION BY buyer_id ORDER BY created_at) for the previous timestamp, then CAST(julianday(created_at) - julianday(previous_order_at) AS INTEGER) for the gap. The first order per buyer has a NULL previous timestamp.

Expected skills

LAG offsets, partition ordering, and date math with julianday.

SQL
Loading...

AI evaluation

Run the SQL query to inspect preview rows.