Find days since a customer’s previous order
Your task
For completed orders, return customer_id, order_id, and days_since_previous as a whole number. Use NULL for the first order. Sequence and sort by customer, date, then order ID.
LAG can supply the previous order date in a customer’s own order history.
Sample data
shop_orders| id | customer_id | ordered_on | channel | status | total_cents |
|---|---|---|---|---|---|
| 201 | 1 | 2025-01-04 | online | completed | 2500 |
| 202 | 2 | 2025-01-10 | store | completed | 1800 |
| 203 | 2 | 2025-01-10 | store | completed | 3200 |
| 204 | 3 | 2025-01-18 | marketplace | refunded | 5000 |
| 205 | 4 | 2025-02-02 | store | completed | 2700 |
| 206 | 1 | 2025-02-04 | online | completed | 4000 |
| 207 | 5 | 2025-02-18 | online | cancelled | 2400 |
| 208 | 6 | 2025-02-28 | online | completed | 1700 |
| 209 | 4 | 2025-03-16 | online | completed | 2900 |
| 210 | 8 | 2025-03-09 | store | completed | 3100 |
Expected output
| customer_id | order_id | days_since_previous |
|---|---|---|
| 1 | 201 | NULL |
| 1 | 206 | 31 |
| 2 | 202 | NULL |
| 2 | 203 | 0 |
| 4 | 205 | NULL |
| 4 | 209 | 42 |
| 6 | 208 | NULL |
| 8 | 210 | NULL |
Show a hint
Use LAG over each customer and subtract the previous JULIANDAY from the current one.
Window functions guide
Keep detail rows while summarizing
GROUP BY would return one row per genre. A window aggregate with PARTITION BY leaves every album in the result and gives each row its genre's average. This makes it easy to compare a row with its peers.
SELECT title, genre, price,
AVG(price) OVER (PARTITION BY genre) AS genre_average
FROM albums;Specify the window order and frame
The ORDER BY inside OVER defines the order of calculation. ROWS defines which neighboring rows contribute. This example adds the current sale to all earlier sales by ID. The last ORDER BY controls the order shown on screen.
SELECT id, quantity,
SUM(quantity) OVER (
ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_quantity
FROM sales
ORDER BY id;Rank first, then filter
Window results are calculated too late for the same SELECT's WHERE clause. Compute a rank in a CTE, then filter the named result. ROW_NUMBER assigns one position per row. RANK gives ties the same position and may leave gaps.
WITH ranked AS (
SELECT title, genre, ROW_NUMBER() OVER (
PARTITION BY genre ORDER BY price, id
) AS position
FROM albums
)
SELECT genre, title FROM ranked WHERE position = 1;Worked solution
SELECT customer_id,id AS order_id,CAST(JULIANDAY(ordered_on)-JULIANDAY(LAG(ordered_on) OVER (PARTITION BY customer_id ORDER BY ordered_on,id)) AS INTEGER) AS days_since_previous FROM shop_orders WHERE status='completed' ORDER BY customer_id,ordered_on,id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
