Window Functions · Problem 78 of 118

Days Between Orders

HardWindow FunctionsShop data

For customers 1 to 3, return customer_id, order_id, order_date and days_since_previous: the whole number of days since the customer's previous order, or NULL for their first order. Order orders by order_date, then order_id. Sort the result by customer_id, order_date, order_id.

Hint 1

LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date, order_id) is the previous order date of the same customer.

Hint 2

JULIANDAY(a) - JULIANDAY(b) gives days.

Reference solution

SELECT customer_id,
       order_id,
       order_date,
       CAST(JULIANDAY(order_date)
            - JULIANDAY(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date, order_id)) AS INTEGER) AS days_since_previous
FROM orders
WHERE customer_id BETWEEN 1 AND 3
ORDER BY customer_id, order_date, order_id;

Without PARTITION BY the window is one long list, so a customer's first order gets the previous row, which belongs to someone else. PARTITION BY customer_id restarts the window for each customer, so the first order correctly gets NULL. Time between events is the basis of churn, retention and "how often do customers return" analysis.