Calculate Monthly Restaurant Sales Growth
DoorDashData Scientist · Technical ScreenLast updated
This problem tests the ability to aggregate transactional data by month and use window functions to calculate percentage growth between consecutive periods while handling null values.
Problem Statement
You are given a table orders containing historical restaurant transaction data. You need to calculate the month-over-month (MoM) sales growth percentage for each restaurant.
Table: orders
| Column | Type | Description |
|---|---|---|
| order_id | integer | Unique identifier |
| restaurant_id | integer | ID of the restaurant |
| sale_amount | decimal | Revenue from the order |
| created_at | timestamp | Date of the transaction |
Task
Write a SQL query to return the restaurant_id, month (in 'YYYY-MM' format), total_monthly_sales, and growth_percentage.
- The
growth_percentageis defined as:(current_month_sales - prior_month_sales) / prior_month_sales * 100. - If a restaurant has no sales in the prior month, the growth percentage should be
NULL. - Order the results by
restaurant_idascending, and then bymonthascending.
Example
Input:
| restaurant_id | sale_amount | created_at |
|---|---|---|
| 1 | 100 | 2023-01-05 |
| 1 | 200 | 2023-02-10 |
Output:
| restaurant_id | month | total_monthly_sales | growth_percentage |
|---|---|---|---|
| 1 | 2023-01 | 100 | NULL |
| 1 | 2023-02 | 200 | 100.0 |
Constraints
- If
prior_month_salesis 0, treat the growth asNULLor handle it gracefully to avoid division errors. - Ensure all months are represented, even if there are no sales in a specific month for a specific restaurant (only consider months where sales > 0).
Hints
Hint 1
Use DATE_TRUNC or TO_CHAR to extract the month and year from the `created_at` timestamp.
Hint 2
Aggregate the sales by `restaurant_id` and `month` using a GROUP BY clause before applying window functions.
Hint 3
Use the `LAG()` window function to fetch the `total_monthly_sales` from the previous month, partitioned by `restaurant_id`.
Follow-up questions
- How would you modify your query to include months where a restaurant had zero sales if you were provided a master calendar table?
- What steps would you take to ensure the query remains performant as the number of transactions grows to billions of rows?
- If the business defines 'growth' differently for new restaurants (e.g., first month is 0% growth), how would you adjust your calculation logic?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.