Compare with the previous order

window functions

Compare with the previous order

Best Buy SQL Interview Question

Best Buy's analytics team wants to see how each online order compares with the one placed just before it.

For every order, show the order_id, the amount, and the amount of the order placed just before it as previous_amount. Use all orders, whatever their status. The first order has no earlier order, so its previous_amount is NULL. Sort the rows by order date, earliest first.

Asked of

  • Product Analyst
  • Data Scientist
  • Analytics Engineer
  • Data Engineer

ordersTable35 rows

Column NameType
order_idBIGINT
customer_idBIGINT
order_dateDATE
statusVARCHAR
amountDOUBLE

ordersExample Input

order_idcustomer_idorder_datestatusamount
100112024-01-05completed120.5
100222024-01-07completed2400
100312024-01-11completed89.99
100432024-01-15canceled45
100542024-01-18completed610.75
100622024-01-22completed1850.25
100752024-01-29completed3200
100812024-02-02refunded75
100962024-02-06completed55.4
101032024-02-09completed132.6

Example Output

order_idamountprevious_amount
1001120.5NULL
10022400120.5
100389.992400
10044589.99
1005610.7545
10061850.25610.75
100732001850.25
1008753200
100955.475
1010132.655.4

Explanation

Order 1002 was placed right after order 1001, so its previous amount is 120.50. Order 1001 is the earliest order, so it has no previous amount.

The example above is a small slice of the data. Your query runs against the full tables.