Summarize Monthly Sales by Region from Transaction Records
SQL & DataAuto-graded · 13 test casesLast updated
Tests group-by aggregation: given a list of transaction dicts, compute total revenue and order count per region per month, returned as a sorted list of summary records.
Monthly Sales Summary by Region
You are given a list of transaction records. Each record is a dictionary with the following keys:
| Key | Type | Description |
|---|---|---|
"date" | str | Transaction date in "YYYY-MM-DD" format |
"region" | str | Region name (non-empty string) |
"amount" | float | Revenue from this transaction (always ≥ 0) |
Write a function that groups these transactions by (year-month, region) and returns a summary list. Each element of the returned list must be a dictionary with exactly these keys:
| Key | Type | Description |
|---|---|---|
"month" | str | Year-month string in "YYYY-MM" format |
"region" | str | Region name |
"total_revenue" | float | Sum of amount for all matching transactions |
"order_count" | int | Number of transactions in this group |
The returned list must be sorted ascending first by "month", then by "region" (lexicographic) as a tie-break.
total_revenue values must be rounded to 2 decimal places.
If the input list is empty, return an empty list.
Constraints
0 ≤ len(transactions) ≤ 2000- Each
"date"is a valid calendar date in"YYYY-MM-DD"format. - Each
"region"is a non-empty string containing only letters, digits, spaces, or hyphens. 0.0 ≤ amount ≤ 1_000_000.0- There is no constraint on the number of distinct regions or months.
Examples
Example 1
Input: monthly_sales_summary([{'date': '2024-03-15', 'region': 'North', 'amount': 120.5}, {'date': '2024-03-22', 'region': 'South', 'amount': 200}, {'date': '2024-03-30', 'region': 'North', 'amount': 80.75}, {'date': '2024-04-05', 'region': 'North', 'amount': 50}])
Output: [{'month': '2024-03', 'region': 'North', 'total_revenue': 201.25, 'order_count': 2}, {'month': '2024-03', 'region': 'South', 'total_revenue': 200, 'order_count': 1}, {'month': '2024-04', 'region': 'North', 'total_revenue': 50, 'order_count': 1}]
Example 2
Input: monthly_sales_summary([{'date': '2023-01-10', 'region': 'East', 'amount': 0}, {'date': '2023-01-10', 'region': 'East', 'amount': 0}])
Output: [{'month': '2023-01', 'region': 'East', 'total_revenue': 0, 'order_count': 2}]
Example 3
Input: monthly_sales_summary([])
Output: []
Hints
Hint 1
Use a dictionary keyed by (month_str, region) to accumulate revenue and count in a single pass over the records.
Hint 2
Extract the year-month string from 'date' by slicing the first 7 characters: date[:7].
Hint 3
After aggregating, convert the dictionary items into the required list of dicts and sort by (month, region) before returning.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a classic group-by aggregation over a flat list of records — the Python equivalent of a SQL GROUP BY month, region with SUM(amount) and COUNT(*).
Steps
-
Extract the grouping key. The year-month can be obtained cheaply by slicing
date[:7], giving a"YYYY-MM"string without any date-parsing overhead. -
Accumulate into a dictionary. Use a
defaultdictkeyed by(month, region)tuples. For each transaction, add itsamountto the running total and increment the count. -
Build the output list. Iterate over the accumulated dictionary, create one result dict per group (rounding
total_revenueto 2 decimal places withround(..., 2)), and append to a list. -
Sort. Sort the result list by
(month, region)to satisfy the tie-break requirement.
Why it is correct
- Every transaction is visited exactly once, so no data is missed or double-counted.
- Python's floating-point addition can accumulate tiny errors;
round(..., 2)corrects these to the required precision. date[:7]is safe because the problem guarantees"YYYY-MM-DD"format.- Case-sensitive region comparison is intentional:
"Beta"and"BETA"are different regions per the problem spec.
Complexity
| Value | |
|---|---|
| Time | O(n log n) — dominated by the final sort; the aggregation pass is O(n) |
| Space | O(g) — where g is the number of distinct (month, region) groups, at most n |
from collections import defaultdict
def monthly_sales_summary(transactions: list) -> list:
groups = defaultdict(lambda: [0.0, 0])
for tx in transactions:
month = tx["date"][:7]
region = tx["region"]
key = (month, region)
groups[key][0] += tx["amount"]
groups[key][1] += 1
result = []
for (month, region), (revenue, count) in groups.items():
result.append({
"month": month,
"region": region,
"total_revenue": round(revenue, 2),
"order_count": count,
})
result.sort(key=lambda r: (r["month"], r["region"]))
return result