Monthly Revenue Summary by Product Category
SQL & DataAuto-graded · 13 test casesLast updated
Tests group-by aggregation over a list of transaction records to compute per-category monthly revenue, count, and average order value.
Monthly Revenue Summary by Product Category
You are given a list of sales transaction records. Each record is a dictionary with the following fields:
| Field | Type | Description |
|---|---|---|
"transaction_id" | str | Unique identifier for the transaction |
"category" | str | Product category name |
"month" | str | Month in "YYYY-MM" format |
"amount" | float | Revenue amount for the transaction (may be negative for refunds) |
"is_cancelled" | bool | If True, this transaction should be excluded entirely |
Write a function that processes these records and returns a summary list, where each entry represents one (category, month) pair.
Processing Rules
- Skip any transaction where
is_cancelledisTrue. - Group remaining transactions by
(category, month). - For each group compute:
"total_revenue": sum ofamount, rounded to 2 decimal places"transaction_count": number of transactions in the group"avg_order_value":total_revenue / transaction_count, rounded to 2 decimal places
- Return the summary list sorted first by
monthascending, then bycategoryascending (both lexicographic). - If all transactions are cancelled (or the input list is empty), return an empty list
[].
Output Format
Each element of the returned list is a dict with exactly these keys:
{
"category": str,
"month": str,
"total_revenue": float,
"transaction_count": int,
"avg_order_value": float
}
Constraints
0 ≤ len(transactions) ≤ 2000- Each
amountsatisfies-10000.0 ≤ amount ≤ 10000.0 categoryis a non-empty string; casing matters ("Books"≠"books")monthis always a valid"YYYY-MM"stringtransaction_idvalues are unique across all records- There is no requirement on how many distinct categories or months exist
Examples
Example 1
Input: monthly_revenue_summary([{'transaction_id': 't1', 'category': 'Books', 'month': '2024-01', 'amount': 29.99, 'is_cancelled': False}, {'transaction_id': 't2', 'category': 'Electronics', 'month': '2024-01', 'amount': 199, 'is_cancelled': False}, {'transaction_id': 't3', 'category': 'Books', 'month': '2024-01', 'amount': 14.99, 'is_cancelled': False}, {'transaction_id': 't4', 'category': 'Books', 'month': '2024-02', 'amount': 9.99, 'is_cancelled': False}, {'transaction_id': 't5', 'category': 'Electronics', 'month': '2024-01', 'amount': 49.99, 'is_cancelled': True}])
Output: [{'category': 'Books', 'month': '2024-01', 'total_revenue': 44.98, 'transaction_count': 2, 'avg_order_value': 22.49}, {'category': 'Electronics', 'month': '2024-01', 'total_revenue': 199, 'transaction_count': 1, 'avg_order_value': 199}, {'category': 'Books', 'month': '2024-02', 'total_revenue': 9.99, 'transaction_count': 1, 'avg_order_value': 9.99}]
Example 2
Input: monthly_revenue_summary([{'transaction_id': 'r1', 'category': 'Clothing', 'month': '2023-11', 'amount': -45, 'is_cancelled': False}, {'transaction_id': 'r2', 'category': 'Clothing', 'month': '2023-11', 'amount': 120, 'is_cancelled': False}, {'transaction_id': 'r3', 'category': 'Clothing', 'month': '2023-11', 'amount': 80, 'is_cancelled': True}])
Output: [{'category': 'Clothing', 'month': '2023-11', 'total_revenue': 75, 'transaction_count': 2, 'avg_order_value': 37.5}]
Example 3
Input: monthly_revenue_summary([])
Output: []
Hints
Hint 1
Use a dictionary keyed by (category, month) tuples to accumulate running totals and counts in a single pass over the non-cancelled records.
Hint 2
After building the aggregation dict, compute avg_order_value from the accumulated total and count before rounding — avoid rounding intermediate values.
Hint 3
Sort the final list with a tuple key: (entry['month'], entry['category']) to satisfy the tie-break rule.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic group-by aggregation task, directly analogous to a SQL query like:
SELECT category, month,
ROUND(SUM(amount), 2) AS total_revenue,
COUNT(*) AS transaction_count,
ROUND(SUM(amount)/COUNT(*),2) AS avg_order_value
FROM transactions
WHERE is_cancelled = FALSE
GROUP BY category, month
ORDER BY month, category;
Algorithm
-
Single-pass accumulation: Iterate over all records. Skip any where
is_cancelledisTrue. For each remaining record, use the pair(category, month)as a dictionary key and accumulate(running_sum, count). -
Compute derived fields: After the pass, for each group compute:
total_revenue = round(sum, 2)avg_order_value = round(sum / count, 2)
It is important to compute
avg_order_valuefrom the raw (unrounded)sumbefore rounding, to avoid compounding rounding error. -
Sort: Sort the result list by
(month, category)— both lexicographic, which aligns with ISO date strings naturally ordering chronologically.
Why it is correct
- Cancellation filtering happens before any aggregation, so cancelled amounts never influence totals.
- Grouping by a tuple key in a
defaultdictcorrectly separates all(category, month)combinations. - Rounding only at the output stage preserves precision during summation.
- The sort key
(month, category)produces a deterministic ordering regardless of insertion order.
Complexity
- Time: O(n log n) — O(n) for the single accumulation pass, O(g log g) for sorting where g ≤ n is the number of distinct groups.
- Space: O(g) for the aggregation dictionary and output list.
Reference Solution
from collections import defaultdict
def monthly_revenue_summary(transactions: list) -> list:
# acc[key] = [sum_amount, count]
acc = defaultdict(lambda: [0.0, 0])
for txn in transactions:
if txn["is_cancelled"]:
continue
key = (txn["category"], txn["month"])
acc[key][0] += txn["amount"]
acc[key][1] += 1
result = []
for (category, month), (total, count) in acc.items():
total_revenue = round(total, 2)
avg_order_value = round(total / count, 2)
result.append({
"category": category,
"month": month,
"total_revenue": total_revenue,
"transaction_count": count,
"avg_order_value": avg_order_value,
})
result.sort(key=lambda x: (x["month"], x["category"]))
return result