← All SQL interview questions
First and last purchase span per customer
HardWindow FunctionsAmazonRazorpay
A lifecycle analysis needs each customer's first and last purchase, the gap in days between them, and how their latest order compares with their own average.
From purchase_history, return one row per customer_code with first_purchase, last_purchase, days_active (days between the two dates), last_amount and avg_amount rounded to 2 decimals. Solve it with window functions rather than a GROUP BY roll-up.
Sample data
Table: purchase_history
16 row(s) · showing first 8
| purchase_idINT | customer_codeTEXT | purchase_dateDATE | amountNUMERIC(10,2) |
|---|---|---|---|
| 1 | CU-01 | 2026-01-04 | 1200.00 |
| 2 | CU-01 | 2026-02-11 | 2400.00 |
| 3 | CU-01 | 2026-03-19 | 900.00 |
| 4 | CU-02 | 2026-01-08 | 5600.00 |
| 5 | CU-02 | 2026-01-29 | 3200.00 |
| 6 | CU-03 | 2026-02-02 | 780.00 |
| 7 | CU-03 | 2026-02-24 | 1450.00 |
| 8 | CU-03 | 2026-04-03 | 2100.00 |
purchase_history
- purchase_idINT
- customer_codeTEXT
- purchase_dateDATE
- amountNUMERIC(10,2)
- Step 1: Define one named window `w` partitioned by customer, ordered by date, with the frame `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`.
- Step 2: The explicit full frame is essential. The default frame for an ordered window stops at the current row, which would make `LAST_VALUE` return the current row instead of the customer's final purchase.
- Step 3: `FIRST_VALUE(purchase_date)` and `LAST_VALUE(purchase_date)` give the lifecycle endpoints; `LAST_VALUE(amount)` picks up the most recent order value.
- Step 4: `AVG(amount) OVER (PARTITION BY customer_code)` computes the per-customer average without collapsing rows.
- Step 5: Window functions repeat the same values on every row of the partition, so add `ROW_NUMBER()` ordered by date descending and keep `rn = 1` to reduce each customer to a single row.
- Step 6: Subtracting two `DATE` values in Postgres yields an integer day count — that becomes `days_active`.
WITH spans AS (
SELECT customer_code,
FIRST_VALUE(purchase_date) OVER w AS first_purchase,
LAST_VALUE(purchase_date) OVER w AS last_purchase,
LAST_VALUE(amount) OVER w AS last_amount,
AVG(amount) OVER (PARTITION BY customer_code) AS avg_amount,
ROW_NUMBER() OVER (
PARTITION BY customer_code ORDER BY purchase_date DESC
) AS rn
FROM purchase_history
WINDOW w AS (
PARTITION BY customer_code
ORDER BY purchase_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)
)
SELECT customer_code,
first_purchase,
last_purchase,
(last_purchase - first_purchase) AS days_active,
last_amount,
ROUND(avg_amount, 2) AS avg_amount
FROM spans
WHERE rn = 1;Learn the concept first
Stuck on Window Functions? These free SQL lessons teach it step by step.
More Window Functions questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program