Retail Reports: Product Revenue Stats and Regional Customer Ranks
SQL & DataAuto-graded · 14 test casesLast updated
Emulate SQL-style reporting in Python: grouped mean and population stddev, NULL-to-zero mapping, inner joins across three tables, and RANK/DENSE_RANK within partitions.
A retail analytics team keeps its data in four tables, passed to you as lists of dictionaries (one dictionary per row):
sales: keyssale_id,store_id,product_id,sale_date,quantity(an integer, orNonefor NULL),revenue.orders: keysorder_id,customer_id,order_date,total_amount.order_items: keysorder_id,product_id,quantity,revenue.customers: keyscustomer_id,region.
Write one function that reproduces the results of the following SQL reports and returns them in a single dictionary.
Report 1: product_stats
Group sales by product_id. For each product, produce a row:
{"product_id": ..., "average_revenue": ..., "stddev_revenue": ...}
average_revenueis the arithmetic mean of that product'srevenuevalues.stddev_revenueis the population standard deviation (divide the sum of squared deviations byn, notn - 1). A product with a single sale therefore has a standard deviation of0.- Rows are sorted by
product_idascending.
Report 2: sales_with_quantity_zero
Return every row of sales in its original order. Each row is a copy of the input row with one extra key, quantity_zero:
- If
quantityisNone(or the key is absent),quantity_zerois0. - Otherwise
quantity_zeroequalsquantity.
All original keys keep their original values (including a None quantity).
Report 3: ranked_customers
Compute the total revenue per customer by inner-joining order_items to orders on order_id, and then to customers on customer_id:
- The revenue summed is
order_items.revenue. Ignoreorders.total_amount. - An item whose
order_idis not inordersis dropped. An item whose order's customer is not incustomersis dropped. - Orders with no items add nothing, and customers with no qualifying items do not appear at all (no zero rows).
Within each region, rank customers by total_revenue from highest to lowest and attach two values:
rank: like SQLRANK(). Customers with equal totals share a rank, and the next distinct total gets the rank equal to its 1-based position (so gaps appear after ties).dense_rank: like SQLDENSE_RANK(). Equal totals share a value, and the next distinct total gets the next integer (no gaps).
Each output row looks like:
{"customer_id": ..., "region": ..., "total_revenue": ..., "rank": ..., "dense_rank": ...}
Rows are sorted by region ascending, then rank ascending, then customer_id ascending.
Return value
A dictionary with exactly the keys "product_stats", "sales_with_quantity_zero" and "ranked_customers", holding the three lists described above. Any input list may be empty, in which case the corresponding output lists are empty.
Constraints
- Each input list has at most 10^5 rows.
customer_id,order_idand (withincustomers/orders) their rows are unique per table.- Revenue values are non-negative numbers.
regionvalues are strings andproduct_id,customer_idare comparable integers.- Do not modify the input rows.
Examples
Example 1
Input: build_retail_reports([{'sale_id': 1, 'store_id': 101, 'product_id': 501, 'sale_date': '2024-06-01', 'quantity': 3, 'revenue': 75}, {'sale_id': 2, 'store_id': 102, 'product_id': 502, 'sale_date': '2024-06-02', 'quantity': None, 'revenue': 40}, {'sale_id': 3, 'store_id': 101, 'product_id': 501, 'sale_date': '2024-06-03', 'quantity': 2, 'revenue': 50}], [{'order_id': 1001, 'customer_id': 2001, 'order_date': '2024-06-01', 'total_amount': 120}, {'order_id': 1002, 'customer_id': 2002, 'order_date': '2024-06-02', 'total_amount': 75}, {'order_id': 1003, 'customer_id': 2001, 'order_date': '2024-06-03', 'total_amount': 50}], [{'order_id': 1001, 'product_id': 501, 'quantity': 2, 'revenue': 50}, {'order_id': 1001, 'product_id': 502, 'quantity': 3, 'revenue': 70}, {'order_id': 1002, 'product_id': 503, 'quantity': 1, 'revenue': 75}], [{'customer_id': 2001, 'region': 'West'}, {'customer_id': 2002, 'region': 'East'}])
Output: {'product_stats': [{'product_id': 501, 'average_revenue': 62.5, 'stddev_revenue': 12.5}, {'product_id': 502, 'average_revenue': 40, 'stddev_revenue': 0}], 'sales_with_quantity_zero': [{'sale_id': 1, 'store_id': 101, 'product_id': 501, 'sale_date': '2024-06-01', 'quantity': 3, 'revenue': 75, 'quantity_zero': 3}, {'sale_id': 2, 'store_id': 102, 'product_id': 502, 'sale_date': '2024-06-02', 'quantity': None, 'revenue': 40, 'quantity_zero': 0}, {'sale_id': 3, 'store_id': 101, 'product_id': 501, 'sale_date': '2024-06-03', 'quantity': 2, 'revenue': 50, 'quantity_zero': 2}], 'ranked_customers': [{'customer_id': 2002, 'region': 'East', 'total_revenue': 75, 'rank': 1, 'dense_rank': 1}, {'customer_id': 2001, 'region': 'West', 'total_revenue': 120, 'rank': 1, 'dense_rank': 1}]}
Hints
Hint 1
Treat each report as its SQL equivalent: GROUP BY with aggregates, a CASE expression, joins plus SUM, then window functions over the aggregated result.
Hint 2
Use the population formula for standard deviation (divide by n). Sum the line-item revenue, not total_amount, and let lookups that fail simply skip the item, which mimics an inner join.
Hint 3
Aggregate first, then group totals by region and sort by (-total, customer_id). Walking the sorted list, update rank to the 1-based position and bump dense_rank only when the total changes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is three independent reports, each a Python version of a common SQL pattern.
Report 1 (GROUP BY with AVG and STDDEV_POP). Bucket revenues by product_id in a dictionary of lists. For each bucket compute the mean, then the population variance (sum of squared deviations divided by n), then its square root. Population rather than sample deviation is required: it makes a single-sale product come out as 0 instead of an undefined value. Sort the result by product_id.
Report 2 (CASE WHEN quantity IS NULL). Copy each sale row and add quantity_zero, which is 0 when the quantity is None or missing and the quantity otherwise. Original order is preserved and the input is not mutated.
Report 3 (joins, SUM, RANK and DENSE_RANK).
- Build two hash maps:
order_id -> customer_idandcustomer_id -> region. - For each order item, look up its customer through the first map and require that customer to exist in the second. Failed lookups are skipped, which is exactly inner-join behavior. Add the item's
revenueto that customer's total. Using line-item revenue means an order without items contributes nothing. - Group the totals by region. Window functions run after aggregation, so ranking happens on these per-customer totals.
- Sort each region's entries by
(-total, customer_id). Walk the sorted list: whenever the total differs from the previous one, setrankto the 1-based position (creating gaps after ties) and incrementdense_rankby one (no gaps). Tied customers keep the same values. - Sort all rows by
(region, rank, customer_id)to match the specified output order.
Why it is correct
Each step mirrors the semantics of the SQL operator it replaces: hashing by key is GROUP BY, failed dictionary lookups are inner-join filtering, and the sorted walk with "change of total" detection is precisely how RANK and DENSE_RANK are defined. Sorting with an explicit customer_id tie-break makes the output deterministic.
Complexity
- Time: O(S + O + I + C + P log P + K log K), where S, O, I, C are the sizes of the four tables, P is the number of products and K the number of customers with revenue. The sorts dominate.
- Space: O(S + O + C + K) for the maps, copied sale rows and grouped totals.
Reference solution
from collections import defaultdict
from math import sqrt
from typing import Dict, List
def build_retail_reports(sales: List[Dict], orders: List[Dict],
order_items: List[Dict], customers: List[Dict]) -> Dict:
# Report 1 and 2: group revenue by product, and map NULL quantity to 0
revenue_by_product = defaultdict(list)
mapped_sales = []
for sale in sales:
revenue_by_product[sale["product_id"]].append(sale["revenue"])
mapped_sales.append({
**sale,
"quantity_zero": 0 if sale.get("quantity") is None else sale["quantity"],
})
product_stats = []
for product_id, values in revenue_by_product.items():
mean = sum(values) / len(values)
variance = sum((v - mean) ** 2 for v in values) / len(values)
product_stats.append({
"product_id": product_id,
"average_revenue": mean,
"stddev_revenue": sqrt(variance),
})
product_stats.sort(key=lambda row: row["product_id"])
# Report 3: inner joins and per-customer totals
region_of = {c["customer_id"]: c["region"] for c in customers}
customer_of_order = {o["order_id"]: o["customer_id"] for o in orders}
totals = defaultdict(int)
for item in order_items:
cid = customer_of_order.get(item["order_id"])
if cid in region_of:
totals[cid] += item["revenue"]
by_region = defaultdict(list)
for cid, total in totals.items():
by_region[region_of[cid]].append((cid, total))
ranked = []
for region, entries in by_region.items():
entries.sort(key=lambda e: (-e[1], e[0]))
prev_total = None
rank = 0
dense = 0
for pos, (cid, total) in enumerate(entries, 1):
if total != prev_total:
rank = pos
dense += 1
ranked.append({
"customer_id": cid,
"region": region,
"total_revenue": total,
"rank": rank,
"dense_rank": dense,
})
prev_total = total
ranked.sort(key=lambda r: (r["region"], r["rank"], r["customer_id"]))
return {
"product_stats": product_stats,
"sales_with_quantity_zero": mapped_sales,
"ranked_customers": ranked,
}