Month-over-Month Revenue Change per Store
SQL & DataAuto-graded · 19 test casesLast updated
Group order records by store and calendar month, then compute each month's percentage change versus the store's previous active month, handling zero totals and gaps.
Month-over-Month Revenue Change per Store
You are given a list of order records for a chain of restaurants. Each record is a dictionary with these keys:
order_id: integer, unique identifier of the orderrestaurant_id: integer, the restaurant that took the ordersale_amount: number, revenue from the ordercreated_at: the time of the order, either adatetimeobject or an ISO-8601 string (for example"2023-01-05T10:00:00")
Produce a monthly summary for every restaurant, including how much its revenue changed relative to the previous month that has data.
Task
-
Group the orders by
restaurant_idand by calendar month. The month label is"YYYY-MM", taken directly from the timestamp as given (do no timezone conversion). If a string ends withZ, treat it as+00:00before parsing. -
For each group, compute
total_monthly_sales, the sum ofsale_amount, accumulated as a float (so a total of 100 is100.0). -
Within each restaurant, go through its months in ascending order. For each month, compute
growth_percentageas:(current_total - previous_total) / previous_total * 100where
previous_totalis the total of the immediately preceding month that appears in the output for that restaurant. Months without any orders do not appear, so if a restaurant has data in January and March only, March is compared to January. -
growth_percentageisNonewhen:- it is the restaurant's earliest month, or
- the previous month's total equals
0.
Negative growth is reported as is (200 followed by 100 gives
-50.0).
Output
Return a list of dictionaries, each with the keys:
restaurant_idmonthtotal_monthly_salesgrowth_percentage
Sort the list by restaurant_id ascending, then by month ascending. If the input is empty, return an empty list.
Constraints
0 <= len(orders) <= 10^5restaurant_idis an integer.sale_amountmay be zero or negative (for example, refunds), so a monthly total can be0.- Timestamps are well-formed ISO-8601 strings or
datetimeobjects. - Only months that contain at least one order appear in the result.
Examples
Example 1
Input: monthly_revenue_change([{'order_id': 1, 'restaurant_id': 1, 'sale_amount': 100, 'created_at': '2023-01-05T10:00:00'}, {'order_id': 2, 'restaurant_id': 1, 'sale_amount': 200, 'created_at': '2023-02-10T10:00:00'}])
Output: [{'restaurant_id': 1, 'month': '2023-01', 'total_monthly_sales': 100, 'growth_percentage': None}, {'restaurant_id': 1, 'month': '2023-02', 'total_monthly_sales': 200, 'growth_percentage': 100}]
Hints
Hint 1
Do the work in two separate stages: first total up sales per (restaurant, month), and only then compare months with each other.
Hint 2
A dictionary keyed by restaurant, holding a dictionary keyed by 'YYYY-MM' strings, works well. Zero-padded year-month strings sort chronologically.
Hint 3
After sorting a restaurant's month keys, the previous element in the sorted list is the comparison month. Guard against the first month and against a previous total of 0 by returning None.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two stages, and keeping them separate is the key.
- Aggregate. Parse each timestamp (accepting strings or
datetimeobjects, and converting a trailingZto+00:00), format it asYYYY-MM, and add the sale amount to a running float total stored undertotals[restaurant_id][month]. - Compare neighbors. For each restaurant (in ascending id order), sort its month keys. Because the labels are zero-padded and fixed width, string order equals chronological order. Walk through the sorted months: the first has no predecessor, so growth is
None. Every other month is compared with the element just before it in the sorted list. If that previous total is0, growth isNone; otherwise it is(current - previous) / previous * 100.
Why it is correct
- Each order contributes to exactly one (restaurant, month) bucket, so each bucket holds the true monthly revenue.
- Only months that have orders are stored, so "previous month" naturally means the previous active month. This matches the rule that gaps are skipped.
- Guarding on a zero previous total avoids division by zero and yields
Noneas required. - Sorting restaurants and months gives the required output order. Negative growth is not clamped.
Complexity
Let n be the number of orders and m the number of distinct (restaurant, month) pairs, with m <= n.
- Time: O(n) to aggregate plus O(m log m) to sort, so O(n + m log m).
- Space: O(m) for the totals and the output.
Reference solution
from typing import List, Dict
from datetime import datetime
from collections import defaultdict
def monthly_revenue_change(orders: List[Dict]) -> List[Dict]:
totals = defaultdict(lambda: defaultdict(float))
for order in orders:
rid = order['restaurant_id']
created = order['created_at']
amount = order['sale_amount']
if isinstance(created, str):
dt = datetime.fromisoformat(created.replace('Z', '+00:00'))
else:
dt = created
totals[rid][dt.strftime('%Y-%m')] += amount
results = []
for rid in sorted(totals.keys()):
months = sorted(totals[rid].keys())
for i, month in enumerate(months):
current = totals[rid][month]
if i == 0:
growth = None
else:
prev = totals[rid][months[i - 1]]
if prev == 0:
growth = None
else:
growth = (current - prev) / prev * 100
results.append({
'restaurant_id': rid,
'month': month,
'total_monthly_sales': current,
'growth_percentage': growth,
})
return results