KatInterview

Aggregate Sales Totals by Month Across a Full Year

SQL & DataAuto-graded · 20 test cases
MediumAuto-gradedSQL & Dataaggregationjoindate-manipulation

Last updated

Tests ability to join two relational datasets, filter by year, and produce a complete 12-row monthly summary including zero-revenue months.

You are given two tables represented as lists of rows.

purchases — one row per transaction header:

Column indexNameTypeDescription
0idintUnique transaction ID
1purchase_datestrDate in "YYYY-MM-DD" format
2customer_idintCustomer identifier

line_items — one row per product within a transaction:

Column indexNameTypeDescription
0idintUnique line-item ID
1purchase_idintForeign key referencing purchases.id
2productstrProduct name
3pricefloatRevenue contributed by this line item

Task

Write a function that returns the total revenue for each calendar month of 2023, as a list of 12 rows ordered by month (January = 1, December = 12).

Each row in the output has the form [month, revenue] where:

  • month is an integer from 1 to 12.
  • revenue is the sum of price across all line items whose parent transaction falls within that month of 2023.
  • Months with no qualifying sales must still appear in the output with revenue = 0.

Revenue belongs to a line item only when its purchase_id matches an existing transaction in purchases and that transaction's date falls in 2023. Transactions that have no line items contribute nothing. Line items whose purchase_id does not match any transaction are ignored.


Constraints

  • 0 <= len(purchases) <= 10^4
  • 0 <= len(line_items) <= 10^5
  • Every purchase_date is a valid date string in "YYYY-MM-DD" format.
  • price values are non-negative floats.
  • Transaction id values within purchases are unique.
  • The output must contain exactly 12 rows, one per month, sorted ascending by month.

Examples

Example 1

Input: monthly_sales_summary([[1, '2023-01-03', 101], [2, '2023-02-14', 102], [3, '2023-02-20', 101]], [[1, 1, 'A', 25], [2, 1, 'B', 15], [3, 2, 'C', 35]])

Output: [[1, 40], [2, 35], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0], [11, 0], [12, 0]]

Hints

Hint 1

Build a lookup from transaction ID to purchase date first — this is equivalent to indexing the left side of a JOIN before iterating the right side.

Hint 2

Pre-populate a dictionary with all 12 month keys set to 0 before processing any line items. A plain GROUP BY only produces rows for months that appear in the data, which misses empty months.

Hint 3

When checking the year, parse the date string and compare the year field directly rather than doing string slicing — it is less error-prone and easier to extend.