Aggregate Sales Totals by Month Across a Full Year
SQL & DataAuto-graded · 20 test casesLast 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 index | Name | Type | Description |
|---|---|---|---|
| 0 | id | int | Unique transaction ID |
| 1 | purchase_date | str | Date in "YYYY-MM-DD" format |
| 2 | customer_id | int | Customer identifier |
line_items — one row per product within a transaction:
| Column index | Name | Type | Description |
|---|---|---|---|
| 0 | id | int | Unique line-item ID |
| 1 | purchase_id | int | Foreign key referencing purchases.id |
| 2 | product | str | Product name |
| 3 | price | float | Revenue 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:
monthis an integer from 1 to 12.revenueis the sum ofpriceacross 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^40 <= len(line_items) <= 10^5- Every
purchase_dateis a valid date string in"YYYY-MM-DD"format. pricevalues are non-negative floats.- Transaction
idvalues withinpurchasesare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge has two parts: linking revenue figures (stored in line_items) to dates (stored in purchases), and ensuring the output always contains all 12 months even when some have no sales.
Step-by-step plan
1. Index purchases by ID.
Scan purchases once and build a dictionary mapping each transaction id to its purchase_date string. This is the Python equivalent of the indexed side of a SQL JOIN — subsequent lookups are O(1) instead of O(n).
2. Pre-populate all 12 month buckets.
Create a dictionary {1: 0, 2: 0, ..., 12: 0} before touching any line item. A naive GROUP BY only emits rows for months that actually appear in the data. By seeding every key upfront, months with zero revenue show up automatically without any special-case logic at the end.
3. Iterate line items and accumulate revenue. For each line item:
- Look up its
purchase_idin the date index. If it is missing, skip it — this matches inner-join semantics (an orphan item has no date and therefore no month). - Parse the date and check
year == 2023. Items belonging to transactions in other years are excluded. - Add
priceto the matching month bucket.
4. Emit the result.
Return [[m, revenue[m]] for m in range(1, 13)] — exactly 12 rows, sorted by month.
Why this is correct
- Join semantics: Only line items whose
purchase_idexists inpurchasescontribute revenue, which is exactly what an inner join produces. - Transactions without line items contribute nothing, because revenue only comes from
pricevalues inline_items. - Year filter: Comparing
datetime.year == 2023is unambiguous and correct across all valid date strings. - Complete output: Because all 12 keys are set before the loop, the final list comprehension always produces 12 rows regardless of the input.
Walking through the sample input:
- Transaction 1 (2023-01-03) has line items priced 25 and 15 → January total = 40.
- Transaction 2 (2023-02-14) has a line item priced 35 → February total = 35.
- Transaction 3 (2023-02-20) has no line items → February stays at 35.
- All other months remain 0.
Result: [[1, 40], [2, 35], [3, 0], ..., [12, 0]].
Complexity
Let n = len(purchases) and k = len(line_items).
- Time: O(n + k). One pass to build the index, one pass over line items with O(1) hash lookups, and a constant 12-iteration output step.
- Space: O(n) for the date index, plus O(1) for the 12 monthly totals.
Edge cases
| Scenario | Behaviour |
|---|---|
| Either input is empty | All 12 months return 0. |
| Transactions dated outside 2023 | Their line items are skipped. |
| Line item with no matching transaction | Skipped (inner-join semantics). |
| Multiple line items in the same month | All prices summed into one bucket. |
| Transaction with no line items | Contributes 0 to its month. |
Full solution
from typing import List
from datetime import datetime
def monthly_sales_summary(purchases: List[List], line_items: List[List]) -> List[List]:
# Step 1: build a map from transaction id -> purchase_date string
# This is the indexed side of the join (equivalent to the "orders" primary key).
date_by_purchase = {}
for row in purchases:
date_by_purchase[row[0]] = row[1]
# Step 2: pre-fill every month of 2023 with zero revenue.
# This guarantees all 12 rows appear even when a month has no sales.
revenue = {m: 0 for m in range(1, 13)}
# Step 3: iterate line items, look up the parent transaction date,
# filter to 2023, and accumulate price into the correct month bucket.
for item in line_items:
purchase_id = item[1]
price = item[3]
if purchase_id not in date_by_purchase:
# Orphan line item — no matching transaction (inner-join semantics).
continue
purchase_date = datetime.strptime(date_by_purchase[purchase_id], "%Y-%m-%d")
if purchase_date.year == 2023:
revenue[purchase_date.month] += price
# Step 4: emit exactly 12 rows in ascending month order.
return [[m, revenue[m]] for m in range(1, 13)]