KatInterview

Summarize Monthly Sales by Region from Transaction Records

SQL & DataAuto-graded · 13 test cases
EasyAuto-gradedSQL & Datadata aggregationdictionariessorting

Last 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:

KeyTypeDescription
"date"strTransaction date in "YYYY-MM-DD" format
"region"strRegion name (non-empty string)
"amount"floatRevenue 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:

KeyTypeDescription
"month"strYear-month string in "YYYY-MM" format
"region"strRegion name
"total_revenue"floatSum of amount for all matching transactions
"order_count"intNumber 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.