Aggregate Sales Report from Transaction Records
SQL & DataAuto-graded · 15 test casesLast updated
Tests the ability to perform group-by aggregation (sum, count, average) over a list of dicts, mimicking SQL GROUP BY with multiple metrics and tie-breaking output order.
Aggregate Sales Report from Transaction Records
You are given a list of transaction records. Each record is a dictionary with the following keys:
"region"— a non-empty string identifying the sales region"product"— a non-empty string identifying the product"units"— a positive integer, the number of units sold"revenue"— a non-negative float, the total revenue for that transaction
Your task is to aggregate these records by (region, product) pair and return a summary table.
What to compute per group
For each unique (region, product) pair produce a dict with exactly these keys:
| Key | Value |
|---|---|
"region" | the region string |
"product" | the product string |
"total_units" | sum of units across all matching transactions |
"total_revenue" | sum of revenue across all matching transactions, rounded to 2 decimal places |
"num_transactions" | count of matching transactions |
"avg_revenue_per_unit" | total_revenue / total_units, rounded to 4 decimal places |
Output ordering
Return the list of summary dicts sorted first by "region" ascending (lexicographic), then by "product" ascending (lexicographic).
Edge cases
- If
transactionsis an empty list, return an empty list. - All
"units"values are guaranteed to be ≥ 1, soavg_revenue_per_unitis always well-defined. - String comparisons are case-sensitive (
"North"and"north"are different regions).
Constraints
0 ≤ len(transactions) ≤ 2000- Each
"region"and"product"string has length between 1 and 50 characters. 1 ≤ units ≤ 10_000per transaction0.0 ≤ revenue ≤ 1_000_000.0per transaction- There may be many transactions mapping to the same
(region, product)pair, or every transaction may be unique.
Examples
Example 1
Input: aggregate_sales([{'region': 'East', 'product': 'Widget', 'units': 10, 'revenue': 150}, {'region': 'West', 'product': 'Gadget', 'units': 5, 'revenue': 80}, {'region': 'East', 'product': 'Widget', 'units': 4, 'revenue': 62.5}])
Output: [{'region': 'East', 'product': 'Widget', 'total_units': 14, 'total_revenue': 212.5, 'num_transactions': 2, 'avg_revenue_per_unit': 15.1786}, {'region': 'West', 'product': 'Gadget', 'total_units': 5, 'total_revenue': 80, 'num_transactions': 1, 'avg_revenue_per_unit': 16}]
Example 2
Input: aggregate_sales([{'region': 'North', 'product': 'Alpha', 'units': 100, 'revenue': 2000}, {'region': 'North', 'product': 'Beta', 'units': 50, 'revenue': 750}, {'region': 'South', 'product': 'Alpha', 'units': 200, 'revenue': 3800}, {'region': 'North', 'product': 'Alpha', 'units': 25, 'revenue': 510.5}])
Output: [{'region': 'North', 'product': 'Alpha', 'total_units': 125, 'total_revenue': 2510.5, 'num_transactions': 2, 'avg_revenue_per_unit': 20.084}, {'region': 'North', 'product': 'Beta', 'total_units': 50, 'total_revenue': 750, 'num_transactions': 1, 'avg_revenue_per_unit': 15}, {'region': 'South', 'product': 'Alpha', 'total_units': 200, 'total_revenue': 3800, 'num_transactions': 1, 'avg_revenue_per_unit': 19}]
Example 3
Input: aggregate_sales([])
Output: []
Hints
Hint 1
Use a dictionary keyed by (region, product) tuples to accumulate running totals as you iterate through the transactions.
Hint 2
After accumulating sums and counts, compute avg_revenue_per_unit from the already-rounded total_revenue divided by total_units, then round the result to 4 decimal places.
Hint 3
Sort the final list using a tuple key (record['region'], record['product']) to satisfy the lexicographic ordering requirement.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a straightforward GROUP BY aggregation — the Python equivalent of:
SELECT region, product,
SUM(units) AS total_units,
ROUND(SUM(revenue),2) AS total_revenue,
COUNT(*) AS num_transactions,
ROUND(SUM(revenue)/SUM(units), 4) AS avg_revenue_per_unit
FROM transactions
GROUP BY region, product
ORDER BY region ASC, product ASC;
Steps
-
Accumulate — Iterate over every transaction. Use a
dictkeyed by the(region, product)tuple to maintain running sums forunits,revenue, and a transaction count. -
Finalize — Once all records are consumed, iterate over the accumulator dict. For each group:
- Round
total_revenueto 2 decimal places. - Compute
avg_revenue_per_unit = total_revenue / total_unitsusing the already-rounded total, then round to 4 decimal places. (Units are guaranteed ≥ 1, so no division-by-zero risk.)
- Round
-
Sort — Sort the result list by
(region, product)lexicographically using Python's stable sort via a tuple key.
Why it is correct
- Python
dictpreserves insertion order but we re-sort, so iteration order of the intermediate dict is irrelevant. - Rounding
total_revenuefirst and then computing the average matches the spec exactly and avoids floating-point accumulation issues from propagating raw floats into the ratio. - Case-sensitive string comparison is Python's default, satisfying the constraint that
"North"≠"north".
Complexity
- Time: O(n log n) — O(n) for the aggregation pass, O(g log g) for sorting where g ≤ n is the number of unique groups. Overall O(n log n).
- Space: O(g) for the accumulator dictionary, where g is the number of unique
(region, product)pairs.
from typing import List, Dict, Any
def aggregate_sales(transactions: list) -> list:
accum = {} # key: (region, product) -> dict of running totals
for tx in transactions:
key = (tx["region"], tx["product"])
if key not in accum:
accum[key] = {
"region": tx["region"],
"product": tx["product"],
"total_units": 0,
"total_revenue": 0.0,
"num_transactions": 0,
}
accum[key]["total_units"] += tx["units"]
accum[key]["total_revenue"] += tx["revenue"]
accum[key]["num_transactions"] += 1
result = []
for (region, product), data in accum.items():
total_revenue = round(data["total_revenue"], 2)
total_units = data["total_units"]
avg_rpu = round(total_revenue / total_units, 4)
result.append({
"region": region,
"product": product,
"total_units": total_units,
"total_revenue": total_revenue,
"num_transactions": data["num_transactions"],
"avg_revenue_per_unit": avg_rpu,
})
result.sort(key=lambda r: (r["region"], r["product"]))
return result