Medium Aggregation Premium

SQL interview question: First and Last Order per Customer

Customer Order Bookends

Analytics wants to compare each customer's first and last purchase to understand behavior evolution.

Show each customer's first order date and last order date, along with days between them.

Return customer_id, first_order, last_order, and days_between (a whole number of days). Use JULIANDAY for date arithmetic.

Skills: MIN/MAX with GROUP BY and date arithmetic

Tables

orders 15 rows
  • order_id integer PK
  • customer_id integer → customers
  • order_date text
  • total_amount real
  • status text
order_idcustomer_idorder_datetotal_amountstatus
11012024-01-20249.99delivered
21012024-03-151999.99delivered
41012024-09-0579.99delivered

Keep going