Order sequence per customer

window functions

Order sequence per customer

Walmart SQL Interview Question

Walmart's product team wants to study how shoppers behave on their first online order compared with later ones.

Number each customer's orders from earliest to latest. Show the order_id, the customer_id, and the position as order_number, where a customer's earliest order is 1. Count every order, whatever its status.

Asked of

  • Data Analyst
  • 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_idcustomer_idorder_number
100111
100221
100312
100431
100541
100622
100751
100813
100961
101032

Explanation

Customer 1 placed orders 1001, 1003 and 1008, in that order by date, so they are numbered 1, 2 and 3. The numbering starts again for every customer, so customer 2's first order, 1002, is also number 1.

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