cswork / libraryOpen practice workspace

Coding questions · DoorDash

Analyze Order Spending Patterns Across Cities Using SQL

This question evaluates proficiency with SQL window functions, time-aware row-level analytics, and the ability to compute intra-group rankings and prior-row comparisons on order data.

Orders

order_id | user_id | order_date | city | order_value

1 | 101 | 2023-01-03 | LA | 23.50

2 | 102 | 2023-01-04 | NY | 45.00

3 | 101 | 2023-01-10 | LA | 19.00

4 | 103 | 2023-01-11 | LA | 55.75

5 | 104 | 2023-01-12 | SF | 32.20

Scenario

An e-commerce marketplace wants detailed insight into order spending patterns across cities.

Question

Using the Orders table, write one SQL query that returns for every order:

  1. order_id, user_id, order_date, city, order_value, 2) previous_order_value of the same user (NULL if first), 3) rank of the order_value within its city ordered from highest to lowest, and
  2. percent_rank of the order_value within its city.
Hints

Combine LAG(), RANK() and PERCENT_RANK() partitioned appropriately; remember to order windows by order_date or order_value as required.

Order analytics with window functions by user and city

Table Orders

columntypeconstraints
order_idINTEGER
user_idINTEGER
order_dateDATE
cityVARCHAR(50)
order_valueDECIMAL(10,2)

Sample data:

cityorder_dateorder_idorder_valueuser_id
LA2023-01-03123.5101
NY2023-01-04245102
LA2023-01-10319101
LA2023-01-11455.75103
SF2023-01-12532.2104

Expected output

For each order, include the order details, the previous order's value by the same user (based on order_date), the rank of order_value within the same city from highest to lowest, and the percent_rank within that city.

cityorder_dateorder_idorder_valuepercent_rank_in_cityprevious_order_valueuser_idvalue_rank_in_city
LA2023-01-03123.50.5NULL1012
NY2023-01-042450NULL1021
LA2023-01-10319123.51013
LA2023-01-11455.750NULL1031
SF2023-01-12532.20NULL1041

Hints

  1. Use LAG(order_value) OVER (PARTITION BY user_id ORDER BY order_date, order_id) to retrieve the previous order value for each user.
  2. Use RANK() and PERCENT_RANK() OVER (PARTITION BY city ORDER BY order_value DESC) to compute within-city rankings.