KatInterview

Summarize Monthly Sales by Region

SQL & DataAuto-graded · 15 test cases
EasyAuto-gradedSQL & Datadata manipulationgroup-byaggregation

Last updated

Tests ability to perform group-by aggregation over a list of transaction records, computing per-region monthly totals and counts.

Monthly Sales Summary by Region

You are given a list of sales transaction records. Each record is a dictionary with the following fields:

  • "region" — a non-empty string identifying the sales region (e.g. "North", "South")
  • "month" — an integer from 1 to 12 representing the calendar month
  • "amount" — a positive float representing the sale amount

Write a function that aggregates these records and returns a summary list. Each entry in the summary corresponds to one unique (region, month) pair that appears in the input, and contains:

  • "region" — the region string
  • "month" — the month integer
  • "total_amount" — the sum of all amount values for that group, rounded to 2 decimal places
  • "num_transactions" — the count of records in that group

The returned list must be sorted ascending first by region (lexicographic), then by month (numeric) as a tie-breaker.

If the input list is empty, return an empty list.

Constraints

  • 0 ≤ len(transactions) ≤ 2000
  • Each "region" is a non-empty string containing only printable ASCII characters.
  • Each "month" is an integer with 1 ≤ month ≤ 12.
  • Each "amount" is a float with 0.0 < amount ≤ 1_000_000.0.
  • Multiple records may share the same (region, month) pair.
  • Region comparison is case-sensitive ("north" and "North" are different regions).

Examples

Example 1

Input: summarize_monthly_sales([{'region': 'North', 'month': 3, 'amount': 120.5}, {'region': 'South', 'month': 3, 'amount': 200}, {'region': 'North', 'month': 3, 'amount': 80.75}, {'region': 'North', 'month': 1, 'amount': 500}])

Output: [{'region': 'North', 'month': 1, 'total_amount': 500, 'num_transactions': 1}, {'region': 'North', 'month': 3, 'total_amount': 201.25, 'num_transactions': 2}, {'region': 'South', 'month': 3, 'total_amount': 200, 'num_transactions': 1}]

Example 2

Input: summarize_monthly_sales([{'region': 'East', 'month': 6, 'amount': 999.99}, {'region': 'East', 'month': 6, 'amount': 0.01}])

Output: [{'region': 'East', 'month': 6, 'total_amount': 1000, 'num_transactions': 2}]

Example 3

Input: summarize_monthly_sales([])

Output: []

Hints

Hint 1

Use a dictionary keyed by (region, month) tuples to accumulate running totals and counts in a single pass.

Hint 2

After building the aggregation dictionary, convert it to a list of result dicts and sort by (region, month).

Hint 3

Remember to round the final total_amount to 2 decimal places — do this after summing all amounts for a group, not during accumulation.