Marketing Channel 90-Day ARPU Comparison
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Growth analysts track customer signups in acquisition and order receipts in transactions. Raw ingestion can occasionally produce exact duplicate (user_id, acquire_channel, acquire_date) rows in acquisition, which should be collapsed so each signup record is counted once.
Each acquired user has a personal 90-day onboarding window spanning acquire_date through acquire_date + 90 days (both endpoints inclusive). Every acquired user in a channel counts toward that channel's user denominator even when they make zero purchases inside their 90-day window.
Write a single SQL query returning one summary row per acquire_channel with the following columns in exact order:
acquire_channel: name of the signup channel.acquired_users: count of distinct(user_id, acquire_channel, acquire_date)signup records in that channel.revenue_90d: totalamountfromtransactionsplaced by those users within their personal 90-day onboarding window (0when no qualifying orders exist), rounded to 2 decimal places.arpu_90d: 90-day average revenue per user (unrounded 90-day channel revenue / acquired_users), rounded to 4 decimal places.is_top_channel:TRUEfor the channel (or all tied channels) achieving the maximumarpu_90dacross the table, andFALSEfor every other channel.
Output rows may appear in any order.
Input Schema
acquisition
| Column | Type | Description |
|---|---|---|
user_id |
INTEGER |
Identifier of the newly acquired user |
acquire_channel |
VARCHAR |
Marketing source credited with the signup |
acquire_date |
DATE |
Calendar date ('YYYY-MM-DD') when the user signed up |
transactions
| Column | Type | Description |
|---|---|---|
transaction_id |
INTEGER |
Unique identifier for each purchase receipt |
user_id |
INTEGER |
Identifier of the purchasing user |
amount |
DECIMAL(10,2) |
Order value |
transaction_date |
DATE |
Calendar date ('YYYY-MM-DD') of the purchase |
Examples
Example 1
Input:
acquisition
user_id |
acquire_channel |
acquire_date |
|---|---|---|
| 201 | referral | 2024-02-01 |
| 202 | referral | 2024-02-10 |
| 203 | search_ads | 2024-02-05 |
| 204 | search_ads | 2024-02-12 |
| 205 | search_ads | 2024-02-15 |
| 206 | newsletter | 2024-02-20 |
transactions
transaction_id |
user_id |
amount |
transaction_date |
|---|---|---|---|
| 501 | 201 | 52.50 | 2024-02-14 |
| 502 | 201 | 27.50 | 2024-03-20 |
| 503 | 203 | 65.00 | 2024-03-01 |
| 504 | 204 | 35.00 | 2024-04-10 |
| 505 | 205 | 90.00 | 2024-06-01 |
| 506 | 206 | 38.00 | 2024-03-05 |
Output:
acquire_channel |
acquired_users |
revenue_90d |
arpu_90d |
is_top_channel |
|---|---|---|---|---|
| newsletter | 1 | 38.0 | 38.0 | FALSE |
| referral | 2 | 80.0 | 40.0 | TRUE |
| search_ads | 3 | 100.0 | 33.3333 | FALSE |
Explanation:
- referral (2 users): user 201 spends 52.50 + 27.50 = 80.00 inside [2024-02-01, 2024-05-01], while user 202 spends 0. Channel revenue_90d = 80.0 and arpu_90d = 80.0 / 2 = 40.0.
- search_ads (3 users): users 203 (65.00) and 204 (35.00) purchase inside their 90-day windows, whereas user 205 (acquired 2024-02-15, window ending 2024-05-15 in leap year 2024) buys on 2024-06-01 (day 107, outside the window). Keeping all 3 acquired users in the denominator yields revenue_90d = 100.0 and arpu_90d = 100.0 / 3 = 33.3333.
- newsletter (1 user): user 206 spends 38.0 on day 14, giving arpu_90d = 38.0.
- 'referral' has the highest arpu_90d (40.0), so it alone receives is_top_channel = TRUE.
Constraints
acquire_dateandtransaction_dateare valid'YYYY-MM-DD'dates;+90 daysfollows true calendar arithmetic (including leap years).- Exact duplicate rows in
acquisitionmust be deduplicated before counting users or summing orders. - Orders dated strictly before
acquire_date, strictly afteracquire_date + 90 days, or belonging touser_ids absent fromacquisitiondo not count. - Whenever two or more channels tie for the highest
arpu_90d, all tied winners must haveis_top_channel = TRUE.
Step-by-step walkthrough
Understand the tables and the 90-day ARPU goal
We have two tables tracking user signups and purchases:
acquisition(user_id, acquire_channel, acquire_date): records which marketing source brought each user in and on what date.transactions(transaction_id, user_id, amount, transaction_date): records individual purchases.
Our goal is to evaluate each channel's 90-day ARPU (Average Revenue Per User — total revenue divided by every acquired user in that channel, including users who spent
$0) and return:acquire_channel: channel name,acquired_users: count of distinct acquired user records in that channel,revenue_90d: totalamountspent by those users fromacquire_datethroughacquire_date + 90 days(both endpoints inclusive), rounded to 2 decimal places,arpu_90d:revenue_90d / acquired_users, rounded to 4 decimal places,is_top_channel:TRUEfor the channel (or tied channels) with the highestarpu_90d,FALSEotherwise.
Row order does not matter.
Why joining and averaging purchases directly gives the wrong answer
A tempting one-liner joins
acquisitiontotransactionsand callsAVG(t.amount):-- Broken in three different ways! SELECT a.acquire_channel, AVG(t.amount) AS arpu FROM acquisition AS a JOIN transactions AS t ON t.user_id = a.user_id GROUP BY a.acquire_channelLook at what goes wrong on
'referral'in Example 1, where User201buys$52.50and$27.50($80.00total) while User202never buys anything ($0):True channel ARPU: ($80.00 + $0) / 2 users = $40.00 per user What the broken query computes instead: 1. INNER JOIN drops User 202 completely (no matching transaction row). 2. AVG(t.amount) averages User 201's two receipts: ($52.50 + $27.50) / 2 = $40.00, or if User 201 had spent $80.00 in one receipt: $80.00 / 1 = $80.00! 3. Purchases made after day 90 (like User 205 on day 107) are wrongly included.To avoid all three traps cleanly, we build the answer in two stages using CTEs (Common Table Expressions — named temporary steps written with
WITH name AS (...)): 1. Compute one row per acquired user with their own 90-day revenue (0when they made no in-window purchases). 2. Aggregate those user rows into one row per channel.Deduplicate acquired users
We start from
acquisitionbecause acquired users define the denominator of ARPU. UsingSELECT DISTINCTremoves exact duplicate log rows ((user_id, acquire_channel, acquire_date)): without it, a duplicated acquisition row would count the same person twice inacquired_usersand pair every one of their purchases twice during the join.WITH acquired AS ( -- Deduplicate exact duplicate acquisition log rows so each acquired user -- counts once in the denominator and does not double-count joined purchases. SELECT DISTINCT user_id, acquire_channel, acquire_date FROM acquisition ),Sum each user's 90-day revenue without dropping non-buyers
Next, we attach in-window purchases using a
LEFT JOIN(a join that keeps every left-side user row even when no right-side purchase matches, fillingNULLs on the right).Crucially, the 90-day date bounds must go inside the
ONclause, not inWHERE. Watch the difference for User205in Example 1, who was acquired on2024-02-15(90-day window ending2024-05-15) and made their only purchase on2024-06-01(day 107, outside the window):If window filter is in ON: acquired row (User 205, 2024-02-15) -> no tx matches ON -> (User 205, amount = NULL) -> kept! revenue = 0 If window filter is in WHERE: LEFT JOIN pairs (User 205, 2024-06-01) -> WHERE rejects 2024-06-01 -> User 205 DELETED from denominator!In SQLite,
DATE(a.acquire_date, '+90 days')adds 90 calendar days (correctly handling month lengths and leap years like 2024). BecauseSUM(t.amount)overNULLs returnsNULL, wrapping it inCOALESCE(..., 0)convertsNULLinto0:user_revenue AS ( -- Keep every acquired user via LEFT JOIN; put the 90-day window inside ON -- (not WHERE!) so users with zero in-window purchases stay with revenue = 0. SELECT a.user_id, a.acquire_channel, COALESCE(SUM(t.amount), 0) AS revenue FROM acquired AS a LEFT JOIN transactions AS t ON t.user_id = a.user_id AND t.transaction_date >= a.acquire_date AND t.transaction_date <= DATE(a.acquire_date, '+90 days') GROUP BY a.user_id, a.acquire_channel, a.acquire_date ),Roll users up into channels and flag the top ARPU
Now
user_revenuehas one row per acquired user, so grouping byacquire_channelis completely straightforward: -COUNT(*)isacquired_users. -ROUND(SUM(revenue), 2)isrevenue_90d. -ROUND(1.0 * SUM(revenue) / COUNT(*), 4)isarpu_90d(multiplying by1.0prevents integer division if every purchase happened to be a whole dollar amount).Finally, how do we flag the highest-ARPU channel — including ties — without collapsing the table? The window function
MAX(arpu_90d) OVER ()(where emptyOVER ()means "compute the maximum across all rows in the result") places the winning ARPU value alongside every channel row. Comparingarpu_90d = MAX(arpu_90d) OVER ()marks every top channel (including ties)TRUEand every other channelFALSE:channel_stats AS ( -- Roll per-user revenue up to one row per channel; 1.0 * forces decimal division. SELECT acquire_channel, COUNT(*) AS acquired_users, ROUND(SUM(revenue), 2) AS revenue_90d, ROUND(1.0 * SUM(revenue) / COUNT(*), 4) AS arpu_90d FROM user_revenue GROUP BY acquire_channel ) -- MAX(arpu_90d) OVER () finds the highest ARPU across all channels so every -- channel tied for first place is flagged TRUE and all others FALSE. SELECT acquire_channel, acquired_users, revenue_90d, arpu_90d, CASE WHEN arpu_90d = MAX(arpu_90d) OVER () THEN TRUE ELSE FALSE END AS is_top_channel FROM channel_statsTrace Example 1 step by step
Let's check every user and purchase in Example 1:
1. Personal 90-day windows (2024 is a leap year, so Feb has 29 days) and user_revenue: user 201 (referral, 2024-02-01 .. 2024-05-01): tx 501 on 2024-02-14 ($52.50) + tx 502 on 2024-03-20 ($27.50) -> revenue = 80.00 user 202 (referral, 2024-02-10 .. 2024-05-10): no purchases -> revenue = 0.00 user 203 (search_ads, 2024-02-05 .. 2024-05-05): tx 503 on 2024-03-01 ($65.00, in window) -> revenue = 65.00 user 204 (search_ads, 2024-02-12 .. 2024-05-12): tx 504 on 2024-04-10 ($35.00, in window) -> revenue = 35.00 user 205 (search_ads, 2024-02-15 .. 2024-05-15): tx 505 on 2024-06-01 ($90.00, day 107 -> outside window!) -> revenue = 0.00 user 206 (newsletter, 2024-02-20 .. 2024-05-20): tx 506 on 2024-03-05 ($38.00, in window) -> revenue = 38.00 2. channel_stats + MAX(arpu_90d) OVER () = 40.0: ('newsletter', 1, 38.0, 38.0, FALSE) ('referral', 2, 80.0, 40.0, TRUE) ('search_ads', 3, 100.0, 33.3333, FALSE)Complete SQL query
WITH acquired AS ( -- Deduplicate exact duplicate acquisition log rows so each acquired user -- counts once in the denominator and does not double-count joined purchases. SELECT DISTINCT user_id, acquire_channel, acquire_date FROM acquisition ), user_revenue AS ( -- Keep every acquired user via LEFT JOIN; put the 90-day window inside ON -- (not WHERE!) so users with zero in-window purchases stay with revenue = 0. SELECT a.user_id, a.acquire_channel, COALESCE(SUM(t.amount), 0) AS revenue FROM acquired AS a LEFT JOIN transactions AS t ON t.user_id = a.user_id AND t.transaction_date >= a.acquire_date AND t.transaction_date <= DATE(a.acquire_date, '+90 days') GROUP BY a.user_id, a.acquire_channel, a.acquire_date ), channel_stats AS ( -- Roll per-user revenue up to one row per channel; 1.0 * forces decimal division. SELECT acquire_channel, COUNT(*) AS acquired_users, ROUND(SUM(revenue), 2) AS revenue_90d, ROUND(1.0 * SUM(revenue) / COUNT(*), 4) AS arpu_90d FROM user_revenue GROUP BY acquire_channel ) -- MAX(arpu_90d) OVER () finds the highest ARPU across all channels so every -- channel tied for first place is flagged TRUE and all others FALSE. SELECT acquire_channel, acquired_users, revenue_90d, arpu_90d, CASE WHEN arpu_90d = MAX(arpu_90d) OVER () THEN TRUE ELSE FALSE END AS is_top_channel FROM channel_stats✅ Submit now — all tests should pass.
Intuition & how it works
Imagine comparing marketing channels (referral, search_ads, newsletter) by handing every newly signed-up user a personal 90-day scorecard the day they join. Every purchase they make between day 0 (acquire_date) and day 90 (acquire_date + 90 days) gets added to their card, and anyone who buys nothing still turns in a card showing $0. Each channel's ARPU (Average Revenue Per User — total revenue divided by all acquired users, buyers and non-buyers alike) is simply the average of all scorecards from that channel, and whichever channel(s) match the highest average earn is_top_channel = TRUE.
The naive shortcut — joining acquisition to transactions with INNER JOIN and calling AVG(amount) — fails in three ways at once: it drops $0 non-buyers from the denominator, averages per checkout receipt (average order value) instead of per person, and ignores each user's personal 90-day window. Putting the date check in WHERE after a LEFT JOIN (a join that preserves left-side rows with NULLs when nothing matches on the right) also silently deletes users whose only purchases happened after day 90. Keeping the 90-day bounds inside LEFT JOIN ... ON, rolling up to one row per user first, and comparing channel ARPUs with the window function MAX(arpu_90d) OVER () (a calculation across all channel rows without collapsing them) avoids every one of those traps.
Here is how that scorecard model works on referral and search_ads in Example 1:
Acquired users:
User 201 (referral, acq 2024-02-01): $52.50 + $27.50 in window -> user revenue = $80.00
User 202 (referral, acq 2024-02-10): no purchases -> user revenue = $0.00
User 203 (search_ads, acq 2024-02-05): $65.00 on 2024-03-01 (in window) -> user revenue = $65.00
User 204 (search_ads, acq 2024-02-12): $35.00 on 2024-04-10 (in window) -> user revenue = $35.00
User 205 (search_ads, acq 2024-02-15): $90.00 on 2024-06-01 (day 107!) -> user revenue = $0.00
Channel rollup + MAX(arpu_90d) OVER () = 40.0:
referral -> 2 users, revenue_90d = 80.0, arpu_90d = 80.0 / 2 = 40.0, is_top_channel = TRUE
search_ads -> 3 users, revenue_90d = 100.0, arpu_90d = 100.0 / 3 = 33.3333, is_top_channel = FALSE
Complexity
Let A be the number of rows in acquisition, U be the number of distinct acquired users (U <= A), T be the number of rows in transactions, and C be the number of channels (C <= U).
- Time:
O(A log A + U log T + K)with a(user_id, transaction_date)index, orO(A + T)with hash aggregation and a hash join. DeduplicatingAacquisition rows takesO(A)with hashing (orO(A log A)by sorting). With a B-tree index ontransactions(user_id, transaction_date), looking up each of theUusers' 90-day slice costsO(log T)plus scanning theKmatching in-window transactions (K <= T). RollingUuser rows intoCchannel rows and scanningCrows once forMAX(arpu_90d) OVER ()addsO(U + C). - Space:
O(U + C). Theacquiredanduser_revenueCTEs (Common Table Expressions — namedWITHsteps) hold one row per distinct acquired user (O(U)), andchannel_statsholds one row per channel (O(C)).
Which indexes help:
transactions(user_id, transaction_date, amount): a covering index (an index holding all columns needed by the join and sum) lets the database jump straight to a user'suser_id, scan only dates betweenacquire_dateandacquire_date + 90 days, and sumamountwithout touching the main table heap.acquisitionis scanned in full because every acquired user belongs in the report, so no selective filter index is needed on it.
Edge cases
- Acquired users with zero purchases: preserved by
LEFT JOIN, givenrevenue = 0viaCOALESCE, and counted inacquired_users, pulling channel ARPU down accurately. - Exact boundary days: purchases on
acquire_date(day 0) and onDATE(acquire_date, '+90 days')(day 90, including across leap-year Februarys such as 2024) count; day-1and day91do not. - Purchases by unacquired
user_ids: ignored becauseacquisitionsits on the left side of theLEFT JOIN. - Multiple channels tied for top ARPU:
arpu_90d = MAX(arpu_90d) OVER ()evaluates toTRUEon every tied channel (including when all channels tie at0.0). - Exact duplicate rows in
acquisition: collapsed bySELECT DISTINCTbefore joining so neitheracquired_usersnorrevenue_90dis doubled. - Channel with zero total revenue: outputs
revenue_90d = 0.0andarpu_90d = 0.0rather thanNULL. - Timestamps instead of pure dates: if
transaction_dateever stored'YYYY-MM-DD HH:MM:SS', text comparison<= '2024-05-15'would miss afternoon purchases on day 90; use the half-open boundtransaction_date < DATE(a.acquire_date, '+91 days')when timestamps are present.
Common mistakes
- Using
INNER JOINbetweenacquisitionandtransactions: drops non-buyers and computes average revenue per paying customer (ARPPU) instead of ARPU. - Using
AVG(t.amount): computes average transaction size rather than revenue per user. - Putting the 90-day date filter in
WHEREafterLEFT JOIN: turns theLEFT JOINback into anINNER JOINfor anyone without an in-window purchase (dropping User205in Example 1 and inflatingsearch_adsARPU from33.3333to50.0). - Using one fixed calendar window instead of
a.acquire_date + 90 days: every user has their own 90-day clock starting on their ownacquire_date. - Integer division in ARPU: writing
SUM(revenue) / COUNT(*)without1.0 *truncates integer sums in SQLite and PostgreSQL. - Using
ORDER BY arpu_90d DESC LIMIT 1to find the top channel: drops all non-winning channels and breaks on ties instead of returning the full table withis_top_channel.
Alternative approaches
- Single-step channel aggregation with
COUNT(DISTINCT a.user_id): onceacquisitionis deduplicated inacquired, you can jointransactionsand group directly byacquire_channel, computingCOUNT(DISTINCT a.user_id)foracquired_usersandRANK() OVER (ORDER BY arpu_90d DESC) = 1foris_top_channel. Note that you still need the deduplicatedacquiredCTE first — otherwise an exact duplicate row inacquisitionwould not changeCOUNT(DISTINCT a.user_id)yet would double that user'sSUM(t.amount)!
sql
WITH acquired AS (
SELECT DISTINCT user_id, acquire_channel, acquire_date
FROM acquisition
),
channel_stats AS (
SELECT
a.acquire_channel,
COUNT(DISTINCT a.user_id) AS acquired_users,
ROUND(COALESCE(SUM(t.amount), 0), 2) AS revenue_90d,
ROUND(1.0 * COALESCE(SUM(t.amount), 0) / COUNT(DISTINCT a.user_id), 4) AS arpu_90d
FROM acquired AS a
LEFT JOIN transactions AS t
ON t.user_id = a.user_id
AND t.transaction_date >= a.acquire_date
AND t.transaction_date <= DATE(a.acquire_date, '+90 days')
GROUP BY a.acquire_channel
)
SELECT
acquire_channel,
acquired_users,
revenue_90d,
arpu_90d,
CASE WHEN RANK() OVER (ORDER BY arpu_90d DESC) = 1 THEN TRUE ELSE FALSE END AS is_top_channel
FROM channel_stats
Follow-up questions
- How would you write a query to rank users within each acquire_channel by lifetime spend and return the top three spenders per channel? Deduplicate
(user_id, acquire_channel)first,LEFT JOINtransactionswithCOALESCE(SUM(t.amount), 0)so channels with fewer than three buyers still list$0acquired users rather than disappearing, and rank inside each channel usingRANK() OVER (PARTITION BY acquire_channel ORDER BY total_spend DESC).RANK()keeps all users tied at 3rd place (useROW_NUMBER()withORDER BY total_spend DESC, user_id ASCif strictly at most three rows per channel are required).
sql
WITH acquired AS (
SELECT DISTINCT user_id, acquire_channel
FROM acquisition
),
user_spend AS (
SELECT
a.acquire_channel,
a.user_id,
COALESCE(SUM(t.amount), 0) AS total_spend
FROM acquired AS a
LEFT JOIN transactions AS t
ON t.user_id = a.user_id
GROUP BY a.acquire_channel, a.user_id
),
ranked AS (
SELECT
acquire_channel,
user_id,
ROUND(total_spend, 2) AS total_spend,
RANK() OVER (
PARTITION BY acquire_channel
ORDER BY total_spend DESC
) AS spend_rank
FROM user_spend
)
SELECT acquire_channel, user_id, total_spend, spend_rank
FROM ranked
WHERE spend_rank <= 3
ORDER BY acquire_channel, spend_rank, user_id
- How would you build a monthly signup-cohort retention report showing the percentage of users in each cohort month who purchase in at least one later calendar month? Truncate
acquire_dateto'YYYY-MM'(strftime('%Y-%m', acquire_date)in SQLite;DATE_TRUNC('month', acquire_date)in PostgreSQL) to form each user'scohort_month, find distinct(user_id, cohort_month)pairs that have at least one order in a strictly later calendar month (strftime('%Y-%m', t.transaction_date) > c.cohort_month), andLEFT JOINback to the cohort so unretained signups stay in the denominator. On Example 1, all6users joined in'2024-02'and5of them (201,203,204,205,206) placed orders in March, April, or June, yielding83.33%retention.
sql
WITH cohort AS (
SELECT DISTINCT
user_id,
strftime('%Y-%m', acquire_date) AS cohort_month
FROM acquisition
),
retained AS (
SELECT DISTINCT
c.user_id,
c.cohort_month
FROM cohort AS c
JOIN transactions AS t
ON t.user_id = c.user_id
WHERE strftime('%Y-%m', t.transaction_date) > c.cohort_month
)
SELECT
c.cohort_month,
COUNT(*) AS cohort_users,
COUNT(r.user_id) AS retained_users,
ROUND(100.0 * COUNT(r.user_id) / COUNT(*), 2) AS retention_pct
FROM cohort AS c
LEFT JOIN retained AS r
ON r.user_id = c.user_id
AND r.cohort_month = c.cohort_month
GROUP BY c.cohort_month
ORDER BY c.cohort_month
- Does leading on 90-day ARPU prove that a marketing channel deserves more budget, or what additional factors should you check first? High 90-day ARPU alone does not justify shifting spend, for three reasons: (1) ARPU ignores Customer Acquisition Cost (CAC) — a channel generating
$40ARPU at$55CAC loses money compared with a$33ARPU channel at$8CAC; (2) small-sample channels have wide confidence intervals where one large order can skew the mean; and (3) observed ARPU reflects average return on past spend, whereas budget reallocation depends on marginal return on the next dollar spent and longer-term retention beyond day 90 (as seen with User205's$90order on day 107).
Follow-up questions
- How would you write a query to rank users within each acquire_channel by lifetime spend and return the top three spenders per channel?
- How would you build a monthly signup-cohort retention report showing the percentage of users in each cohort month who purchase in at least one later calendar month?
- Does leading on 90-day ARPU prove that a marketing channel deserves more budget, or what additional factors should you check first?
Similar questions
- Thirty-Day User Activation by Signup Cohort
- Trailing Four-Week Spend Ranks and Drops
- Experiment Funnel Metrics and SRM Check in SQL
- Segmented Rollout Decision Under Profit and CAC Trade-Offs
- Leading a Zero-to-One Product Initiative
- Experimentation Plan Under Overlapping Marketing and Logging Bugs
More Chime interview questions
- Segmented Rollout Decision Under Profit and CAC Trade-Offs Medium
- Load Balancing, Multi-Tier Caching, and Idempotent APIs Easy
- Segmented Launch Metrics for a Spending Tracker Experiment Medium Pro
- Backend Fundamentals: Async I/O, Go Concurrency, and Database Engines Easy Pro
- Pitching New Product Ideas and Driving Cross-Functional Buy-In Medium Pro
- Stack-Toppling Board Game Simulator Medium Pro
- Trailing Four-Week Spend Ranks and Drops Medium Pro
- Thirty-Day User Activation by Signup Cohort Medium Pro
- Leading a Zero-to-One Product Initiative Medium Pro
- Experimentation Plan Under Overlapping Marketing and Logging Bugs Medium Pro