12/34
Part 3 of 6 · LAG and datesLearn and do
Days to the second order: keep row 1, and keep the NULLs
Now the days from each user's first order to their second. Number the rows, read the next date with LEAD, and keep row 1:
SELECT user_id, days FROM (
SELECT user_id,
CAST(julianday(LEAD(ordered_on) OVER w) - julianday(ordered_on)
AS INTEGER) AS days,
ROW_NUMBER() OVER w AS n
FROM orders
WINDOW w AS (PARTITION BY user_id ORDER BY ordered_on, order_id)
)
WHERE n = 1
ORDER BY user_id;
| user_id | days |
|---|---|
| 1 | 1 |
| 2 | 8 |
| 3 | NULL |
| 4 | NULL |
Users 3 and 4 ordered once. LEAD finds no next row, so their days are NULL. And NULL is the right answer: the question asks for every user, and no second order is what happened.
Filter on the row number, never on the value. Change the filter to WHERE n = 1 AND days IS NOT NULL, and the same query returns only users 1 and 2.
In the editor, write DAYS_TO_NEXT: the days until each user's next order, NULL on their last.