Multi-Year Sales Analysis by Customer Demographics
SQL & DataAuto-graded · 14 test casesLast updated
Tests data joining, deduplication, cohort segmentation, conditional aggregation, and percentage calculations across multiple tables.
You are given four tables representing an e-commerce database:
orders: [order_id, user_id, order_date]
order_items: [order_id, product_id, qty]
products: [product_id, name, category]
users: [user_id, age, location]
Each table is provided as a list of rows. Date strings are in ISO format (YYYY-MM-DD).
Compute three metrics and return them in a dictionary:
Part 1: Subscription Order Percentage (2024)
Calculate what percentage of orders placed in calendar year 2024 included at least one product with category = 'Subscription'. An order containing multiple subscription products should be counted only once. Round the result to two decimal places.
Return this value in the key pct_subscription_2024.
Part 2: Year-over-Year Order Growth by Demographic Cohort
Segment users into age groups:
'18-29': ages 18 through 29 inclusive'30-44': ages 30 through 44 inclusive'45+': ages 45 and above
For each combination of (location, age_group) that appears in the data, compute:
- The count of distinct orders placed in 2023
- The count of distinct orders placed in 2024
- The year-over-year percentage change:
(orders_2024 - orders_2023) / orders_2023
If orders_2023 is zero, set yoy_pct_change to None (null). An order is attributed to the user's current age and location.
Return a list of dictionaries sorted by (location, age_group), each containing:
{'location': str, 'age_group': str, 'orders_2023': int, 'orders_2024': int, 'yoy_pct_change': float or None}
Store this list in the key yoy_by_cohort.
Part 3: Unique Users Who Purchased "Pro" Products in 2024
Identify all users who purchased at least one product in 2024 whose name contains the substring 'pro' (case-insensitive). For each (location, age_group) cohort that has such users, count the number of unique users.
Return a list of dictionaries sorted by:
unique_usersdescendinglocationascending (tie-breaker)age_groupascending (tie-breaker)
Each dictionary contains:
{'location': str, 'age_group': str, 'unique_users': int}
Store this list in the key python_pro_users_by_cohort.
Constraints
- 1 ≤ number of orders ≤ 10,000
- 1 ≤ number of order_items ≤ 50,000
- 1 ≤ number of products ≤ 1,000
- 1 ≤ number of users ≤ 10,000
- All IDs are positive integers
- Dates are valid ISO strings (YYYY-MM-DD)
- Ages are between 18 and 100
- An order may have zero items (edge case)
- A product_id in order_items may not exist in products (handle gracefully)
- A user_id in orders may not exist in users (skip such orders)
Examples
Example 1
Input: analyze_sales_by_demographics([[1, 101, '2023-01-10'], [2, 102, '2023-05-03'], [3, 101, '2024-02-12'], [4, 103, '2024-11-20'], [5, 104, '2024-12-28']], [[1, 10, 1], [1, 11, 2], [2, 11, 1], [3, 12, 1], [4, 10, 1], [5, 13, 1]], [[10, 'Widget Pro', 'Subscription'], [11, 'Widget', 'Standard'], [12, 'Gadget Pro', 'Subscription'], [13, 'Service', 'Standard']], [[101, 27, 'NY'], [102, 42, 'CA'], [103, 35, 'NY'], [104, 23, 'TX']])
Output: {'pct_subscription_2024': 66.67, 'yoy_by_cohort': [{'location': 'CA', 'age_group': '30-44', 'orders_2023': 1, 'orders_2024': 0, 'yoy_pct_change': -1}, {'location': 'NY', 'age_group': '18-29', 'orders_2023': 1, 'orders_2024': 1, 'yoy_pct_change': 0}, {'location': 'NY', 'age_group': '30-44', 'orders_2023': 0, 'orders_2024': 1, 'yoy_pct_change': None}, {'location': 'TX', 'age_group': '18-29', 'orders_2023': 0, 'orders_2024': 1, 'yoy_pct_change': None}], 'python_pro_users_by_cohort': [{'location': 'NY', 'age_group': '18-29', 'unique_users': 1}, {'location': 'NY', 'age_group': '30-44', 'unique_users': 1}]}
Hints
Hint 1
Joining orders to order_items creates one row per item. Use distinct order_id after filtering to avoid double-counting orders with multiple subscription products.
Hint 2
Build lookup dictionaries for products and users by ID to avoid repeated linear scans. Use defaultdict to group items by order_id upfront.
Hint 3
For Part 2, collect order IDs into sets indexed by (location, age_group, year) so deduplication is automatic. For Part 3, collect user IDs into sets to ensure each user is counted once per cohort.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires careful handling of table joins that create data fan-out (one order maps to many items), followed by deduplication to count distinct orders or users.
Strategy
Build efficient lookups first. Create dictionaries mapping product_id and user_id to their full rows, and group order_items by order_id. This prevents expensive repeated scans through lists.
Parse dates once. Extract the year from each order date upfront and store tuples of (order_id, user_id, year) to avoid redundant parsing in each part.
Use sets for automatic deduplication. Throughout all three parts, collect order IDs and user IDs into sets. This makes deduplication structural rather than requiring explicit distinct operations.
Part 1: Subscription Percentage
Collect all 2024 order IDs into a set (the denominator). For each such order, check whether any of its items reference a Subscription product. Collect matching order IDs into a second set (the numerator). Divide and multiply by 100 to express as a percentage, then round to two decimals. Handle the empty case by checking if the denominator is zero.
Part 2: Year-over-Year Growth by Cohort
For each order in 2023 or 2024, look up the user and determine their age group using the bucket boundaries. Use a nested dictionary keyed by (location, age_group) that maps to a two-element list holding sets of 2023 and 2024 order IDs respectively. After processing all orders, iterate through cohorts in sorted order, compute counts from set sizes, and calculate YoY change as (2024 - 2023) / 2023. Return None when the 2023 count is zero to avoid division by zero.
Part 3: Pro Product Users
Scan 2024 orders and identify users who purchased any product whose name contains "pro" (case-insensitive substring match). Collect these user IDs into a set. Group users by (location, age_group) using sets to deduplicate. Convert to a list of dictionaries with unique user counts, then sort by count descending, breaking ties by location and age_group ascending.
Complexity
- Time: O(O + I + P + U) where O is orders, I is items, P is products, U is users. Each table is scanned a constant number of times. Sorting cohorts and results is O(C log C) where C is the number of cohorts, which is bounded by locations × age groups (typically small).
- Space: O(O + I + P + U) for lookup tables, item groupings, and sets of order/user IDs.
Implementation
from collections import defaultdict
from datetime import date
from typing import Dict, List
def analyze_sales_by_demographics(orders, order_items, products, users):
# Build lookup tables
product_by_id = {row[0]: row for row in products}
user_by_id = {row[0]: row for row in users}
# Group items by order to avoid repeated lookups
items_by_order = defaultdict(list)
for order_id, product_id, _qty in order_items:
items_by_order[order_id].append(product_id)
# Parse order dates once
parsed_orders = []
for order_id, user_id, order_date in orders:
year = date.fromisoformat(order_date[:10]).year
parsed_orders.append((order_id, user_id, year))
# Part 1: Subscription percentage in 2024
orders_2024 = {order_id for order_id, _user_id, year in parsed_orders if year == 2024}
subscription_orders = {
order_id
for order_id in orders_2024
if any(product_by_id.get(pid, [None, None, None])[2] == 'Subscription'
for pid in items_by_order[order_id])
}
pct_subscription_2024 = round(100.0 * len(subscription_orders) / len(orders_2024), 2) if orders_2024 else 0.0
# Part 2: YoY growth by cohort
cohort_counts = defaultdict(lambda: [set(), set()])
for order_id, user_id, year in parsed_orders:
if year not in (2023, 2024) or user_id not in user_by_id:
continue
_uid, age, location = user_by_id[user_id]
age_group = '18-29' if 18 <= age <= 29 else '30-44' if 30 <= age <= 44 else '45+'
cohort_counts[(location, age_group)][year - 2023].add(order_id)
yoy_by_cohort = []
for (location, age_group), counts in sorted(cohort_counts.items()):
count_2023, count_2024 = len(counts[0]), len(counts[1])
yoy = (count_2024 - count_2023) / count_2023 if count_2023 else None
yoy_by_cohort.append({
'location': location,
'age_group': age_group,
'orders_2023': count_2023,
'orders_2024': count_2024,
'yoy_pct_change': yoy,
})
# Part 3: Pro product users in 2024
pro_users = set()
for order_id, user_id, year in parsed_orders:
if year != 2024:
continue
if any('pro' in str(product_by_id.get(pid, [None, ''])[1]).casefold()
for pid in items_by_order[order_id]):
pro_users.add(user_id)
python_counts = defaultdict(set)
for user_id in pro_users:
if user_id not in user_by_id:
continue
_uid, age, location = user_by_id[user_id]
age_group = '18-29' if 18 <= age <= 29 else '30-44' if 30 <= age <= 44 else '45+'
python_counts[(location, age_group)].add(user_id)
python_result = [
{'location': location, 'age_group': age_group, 'unique_users': len(user_ids)}
for (location, age_group), user_ids in python_counts.items()
]
python_result.sort(key=lambda row: (-row['unique_users'], row['location'], row['age_group']))
return {
'pct_subscription_2024': pct_subscription_2024,
'yoy_by_cohort': yoy_by_cohort,
'python_pro_users_by_cohort': python_result,
}