Daily SHOP vs WEBSITE Revenue Mix and Efficiency Report
SQL & DataAuto-graded · 15 test casesLast updated
Aggregate two event tables over a 30-day window, fill missing rows with zeros, and compute safe-division shares and revenue-per-conversion per day and destination.
Daily SHOP vs WEBSITE mix report
An advertising team sends users from ads to one of two destinations: a hosted storefront ("SHOP") or the advertiser's own site ("WEBSITE"). Two logs record what each destination earned.
Write a function that turns the two logs into a daily summary for the most recent 30 days of data.
Inputs
revenue_rows: a list of dicts, each with:event_date: string inYYYY-MM-DDformatadvertiser_id: integerdestination:"SHOP"or"WEBSITE"revenue_usd: number (attributed revenue)
conversion_rows: a list of dicts, each with:event_date: string inYYYY-MM-DDformatadvertiser_id: integerdestination:"SHOP"or"WEBSITE"conversions: non-negative integer
Rules
- Window. Let
endbe the latestevent_datefound across both inputs combined. The window is the 30 calendar days ending atend, inclusive, so it starts atend - 29 days. Rows outside the window are ignored. - Combining rows. Several advertisers may report for the same date and destination. Sum them to get one revenue value and one conversion value per
(event_date, destination). - Active dates. A date is active if, inside the window, it appears in at least one of the two inputs. Report only active dates, in ascending order. Do not invent dates that have no rows at all.
- Missing data counts as zero. If a destination has no revenue (or no conversions) on an active date, treat that value as
0. - Zero denominators give
None. Any ratio whose denominator is zero must beNone, not0.
Output
Return a dict with two lists.
"shop_share" has one entry per active date, ascending, each with:
event_date: the date stringshop_revenue: total revenue for"SHOP"that daytotal_revenue: total revenue across both destinations that dayshop_revenue_share:shop_revenue / total_revenue, orNoneiftotal_revenueis 0
"performance" has, for every active date (ascending), exactly two entries: first "SHOP", then "WEBSITE". Each entry has:
event_datedestinationrevenue_usd: that destination's revenue that dayconversions: that destination's conversions that dayrevenue_per_conversion:revenue_usd / conversions, orNoneifconversionsis 0revenue_share:revenue_usddivided by the day's total revenue across destinations, orNoneif that total is 0conversion_share:conversionsdivided by the day's total conversions across destinations, orNoneif that total is 0
If both inputs are empty, return {"shop_share": [], "performance": []}.
Constraints
0 <= len(revenue_rows), len(conversion_rows) <= 10^5- Dates are valid ISO dates (
YYYY-MM-DD). destinationis always"SHOP"or"WEBSITE".revenue_usd >= 0andconversions >= 0.- Use ordinary true division for ratios (no rounding).
Examples
Example 1
Input: summarize_shop_mix([{'event_date': '2025-03-01', 'advertiser_id': 1, 'destination': 'SHOP', 'revenue_usd': 120}, {'event_date': '2025-03-01', 'advertiser_id': 1, 'destination': 'WEBSITE', 'revenue_usd': 80}], [{'event_date': '2025-03-01', 'advertiser_id': 1, 'destination': 'SHOP', 'conversions': 4}, {'event_date': '2025-03-01', 'advertiser_id': 1, 'destination': 'WEBSITE', 'conversions': 2}])
Output: {'shop_share': [{'event_date': '2025-03-01', 'shop_revenue': 120, 'total_revenue': 200, 'shop_revenue_share': 0.6}], 'performance': [{'event_date': '2025-03-01', 'destination': 'SHOP', 'revenue_usd': 120, 'conversions': 4, 'revenue_per_conversion': 30, 'revenue_share': 0.6, 'conversion_share': 0.6666666666666666}, {'event_date': '2025-03-01', 'destination': 'WEBSITE', 'revenue_usd': 80, 'conversions': 2, 'revenue_per_conversion': 40, 'revenue_share': 0.4, 'conversion_share': 0.3333333333333333}]}
Example 2
Input: summarize_shop_mix([{'event_date': '2025-04-10', 'advertiser_id': 2, 'destination': 'SHOP', 'revenue_usd': 0}], [{'event_date': '2025-04-10', 'advertiser_id': 2, 'destination': 'SHOP', 'conversions': 0}])
Output: {'shop_share': [{'event_date': '2025-04-10', 'shop_revenue': 0, 'total_revenue': 0, 'shop_revenue_share': None}], 'performance': [{'event_date': '2025-04-10', 'destination': 'SHOP', 'revenue_usd': 0, 'conversions': 0, 'revenue_per_conversion': None, 'revenue_share': None, 'conversion_share': None}, {'event_date': '2025-04-10', 'destination': 'WEBSITE', 'revenue_usd': 0, 'conversions': 0, 'revenue_per_conversion': None, 'revenue_share': None, 'conversion_share': None}]}
Hints
Hint 1
First find the newest date across both lists together, then subtract 29 days to get the window start. ISO date strings can be parsed with `datetime.date.fromisoformat`.
Hint 2
Build two dictionaries keyed by `(event_date, destination)` that sum revenue and conversions over all advertisers, keeping only rows in the window. Use `.get(key, 0)` so missing rows act as zeros.
Hint 3
The active dates are the union of the dates seen in both dictionaries. For each one, compute the daily totals once, then emit SHOP and WEBSITE rows, returning `None` whenever a denominator is 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a small data pipeline: pick the window, aggregate, align, then compute ratios safely.
- Find the window. Parse every date from both inputs and take the maximum as
end. The window starts atend - 29 days, which gives 30 calendar days inclusive. Using the maximum over both inputs means that if one log lags behind the other, the window does not shrink. - Aggregate. Walk each input once. For rows inside the window, add the value into a dictionary keyed by
(event_date, destination). This sums across advertisers, so the same date and destination reported by several advertisers collapses to one number. - Daily totals. Walk each dictionary once to get total revenue and total conversions per date. Computing these up front avoids rescanning the dictionaries for every date.
- Active dates. Take the union of the dates seen in the revenue and conversion dictionaries and sort them. A day with conversions but no revenue still appears, and days with no rows at all do not.
- Emit rows. For each active date, build one
shop_shareentry and twoperformanceentries (SHOP first, then WEBSITE). Missing keys default to0through.get(key, 0). - Safe division. Every ratio returns
Nonewhen its denominator is0. A share of0would claim a destination got nothing, whereasNonesays there was nothing to split.
Why it is correct
- The window is anchored on the newest data, so exactly the intended 30 dates are considered, and older rows are dropped.
- Summing per
(date, destination)handles any number of advertisers without double counting. - Defaulting missing entries to zero guarantees both destinations appear on every active date.
- Shares use the daily total across destinations as the denominator, so they sum to 1 whenever that total is nonzero.
Complexity
- Time: O((R + C) + D log D), where R and C are the row counts and D <= 30 is the number of active dates. The sort over D is trivial.
- Space: O(D), since after aggregation there are at most 60 keys per dictionary.
Reference solution
from datetime import date, timedelta
from typing import Dict, List
def summarize_shop_mix(revenue_rows: List[Dict], conversion_rows: List[Dict]) -> Dict[str, List[Dict]]:
if not revenue_rows and not conversion_rows:
return {"shop_share": [], "performance": []}
# Window: 30 calendar days ending at the newest date across both inputs.
all_dates = [date.fromisoformat(r["event_date"]) for r in revenue_rows + conversion_rows]
end = max(all_dates)
start = end - timedelta(days=29)
# Collapse advertisers: one value per (event_date, destination).
revenue = {}
conversions = {}
for r in revenue_rows:
d = date.fromisoformat(r["event_date"])
if start <= d <= end:
key = (r["event_date"], r["destination"])
revenue[key] = revenue.get(key, 0) + r["revenue_usd"]
for r in conversion_rows:
d = date.fromisoformat(r["event_date"])
if start <= d <= end:
key = (r["event_date"], r["destination"])
conversions[key] = conversions.get(key, 0) + r["conversions"]
# Daily totals across destinations.
rev_total = {}
for (day, _), value in revenue.items():
rev_total[day] = rev_total.get(day, 0) + value
conv_total = {}
for (day, _), value in conversions.items():
conv_total[day] = conv_total.get(day, 0) + value
active_dates = sorted({d for d, _ in revenue} | {d for d, _ in conversions})
shop_share = []
performance = []
for day in active_dates:
total_rev = rev_total.get(day, 0)
total_conv = conv_total.get(day, 0)
shop_rev = revenue.get((day, "SHOP"), 0)
shop_share.append({
"event_date": day,
"shop_revenue": shop_rev,
"total_revenue": total_rev,
"shop_revenue_share": shop_rev / total_rev if total_rev else None,
})
for destination in ("SHOP", "WEBSITE"):
rev = revenue.get((day, destination), 0)
conv = conversions.get((day, destination), 0)
performance.append({
"event_date": day,
"destination": destination,
"revenue_usd": rev,
"conversions": conv,
"revenue_per_conversion": rev / conv if conv else None,
"revenue_share": rev / total_rev if total_rev else None,
"conversion_share": conv / total_conv if total_conv else None,
})
return {"shop_share": shop_share, "performance": performance}