← 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_idINTcustomer_codeTEXTpurchase_dateDATEamountNUMERIC(10,2)
1CU-012026-01-041200.00
2CU-012026-02-112400.00
3CU-012026-03-19900.00
4CU-022026-01-085600.00
5CU-022026-01-293200.00
6CU-032026-02-02780.00
7CU-032026-02-241450.00
8CU-032026-04-032100.00