Compare Acquisition Channels by Spend, Retention, and Early Revenue
SQL & DataModel answerLast updated
Write SQL to profile marketing channels across four dimensions: user counts, top spenders, cohort retention, and 90-day ARPU.
Channel Performance Analysis
An e-commerce company tracks how users arrive on the platform and what they buy afterward. You have two tables.
signups
| user_id | channel | signup_date |
|---|---|---|
| 101 | organic | 2023-01-05 |
| 102 | paid_search | 2023-01-06 |
| 103 | social_media | 2023-01-08 |
orders
| order_id | user_id | amount | order_date |
|---|---|---|---|
| 9001 | 101 | 45.50 | 2023-01-10 |
| 9002 | 101 | 19.00 | 2023-02-05 |
| 9003 | 102 | 60.00 | 2023-02-12 |
| 9004 | 103 | 30.00 | 2023-03-01 |
The growth team wants to understand which channels bring in the most valuable users. Write SQL to answer each of the following questions. For each part, state any assumptions you make before showing the query.
Part 1 — Channel size Return each channel alongside the number of distinct users who signed up through it.
Part 2 — Top spenders per channel For each channel, find the three highest-spending users and show their total spend. Explain how you handle ties.
Part 3 — Cohort retention Group users by the calendar month they signed up. For each cohort, calculate the percentage who placed at least one order in any later calendar month. A purchase in the same month as signup does not count as retention.
Part 4 — Early revenue by channel For each channel, compute average revenue per user (ARPU) using only orders placed within 90 days of a user's signup date. Identify the channel with the highest ARPU. Include users who placed no orders (they contribute 0 to the average).
You may use CTEs, window functions, DATE_TRUNC, and INTERVAL syntax. A Python/pandas sketch for any one part is a bonus.
Hints
Hint 1
Start every part by joining signups to orders with a LEFT JOIN so users who never ordered still appear in aggregations. Moving date-range conditions into the ON clause instead of WHERE preserves those zero-revenue users.
Hint 2
For Part 2, aggregate to one row per user before ranking. Applying RANK() directly on the orders table gives one row per order, not per user. Decide between RANK (keeps all ties), ROW_NUMBER (exactly 3, needs a tiebreaker), and DENSE_RANK (top 3 distinct spend values), and say which you chose and why.
Hint 3
For Part 3, the retention denominator is all users in the cohort, not just those who bought something. Use DATE_TRUNC to align both signup and order dates to month boundaries, then compare months with > rather than >= to exclude the signup month itself.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Assumptions
State these before writing a single line of SQL — interviewers consistently reward this habit.
- One signup row per user. If duplicates exist, keep the earliest
signup_dateusingROW_NUMBER() OVER (PARTITION BY user_id ORDER BY signup_date). - Zero-order users count. They contribute 0 to spend totals and ARPU, and they sit in every retention denominator.
- Retention excludes the signup month. Buying in the same calendar month as signup does not count.
- The 90-day window is
[signup_date, signup_date + 90 days). Orders dated beforesignup_dateare data errors and are excluded. - No refunds in the sample. In production, ask whether negative amounts should be netted or dropped.
Part 1 — Distinct Users per Channel
SELECT channel,
COUNT(DISTINCT user_id) AS users_signed_up
FROM signups
GROUP BY channel
ORDER BY users_signed_up DESC;
COUNT(DISTINCT ...) guards against duplicate signup rows without a separate deduplication step.
Part 2 — Top 3 Spenders per Channel
WITH user_spend AS (
SELECT s.channel,
s.user_id,
COALESCE(SUM(o.amount), 0) AS total_spend
FROM signups s
LEFT JOIN orders o ON o.user_id = s.user_id
GROUP BY s.channel, s.user_id
),
ranked AS (
SELECT *,
RANK() OVER (PARTITION BY channel
ORDER BY total_spend DESC) AS spend_rank
FROM user_spend
)
SELECT channel, user_id, total_spend, spend_rank
FROM ranked
WHERE spend_rank <= 3
ORDER BY channel, spend_rank;
Why aggregate before ranking. If you apply a window function directly to the orders table you get one row per order, which makes SUM() OVER a running total rather than a per-user total.
Tie-breaking options:
| Function | What it returns |
|---|---|
RANK() | All tied users; a channel may return more than 3 rows |
ROW_NUMBER() | Exactly 3 rows; add a stable tiebreaker (e.g., user_id) to make it deterministic |
DENSE_RANK() | The top 3 distinct spend levels |
RANK() is the safest default for an analytics question because it does not silently discard tied users.
Part 3 — Monthly Cohort Retention
WITH cohort AS (
SELECT user_id,
DATE_TRUNC('month', signup_date) AS cohort_month
FROM signups
),
retained AS (
-- one row per user who bought in any month after their cohort month
SELECT DISTINCT c.user_id
FROM cohort c
JOIN orders o
ON o.user_id = c.user_id
AND DATE_TRUNC('month', o.order_date) > c.cohort_month
)
SELECT c.cohort_month,
COUNT(*) AS cohort_size,
COUNT(r.user_id) AS retained_users,
ROUND(100.0 * COUNT(r.user_id) / COUNT(*), 2) AS retention_pct
FROM cohort c
LEFT JOIN retained r ON r.user_id = c.user_id
GROUP BY c.cohort_month
ORDER BY c.cohort_month;
Three correctness details worth mentioning:
DISTINCTinretainedcollapses multiple later purchases to one row per user, so heavy buyers are not counted multiple times.LEFT JOINkeeps non-retained users inCOUNT(*)— the denominator.100.0forces floating-point division; integer division would truncate every retention rate below 100 % to 0.
On the sample data: all three users are in the 2023-01 cohort. Users 101 and 102 bought in February, user 103 in March. Retention = 3/3 = 100 %.
Common follow-up: "Show retention at each month offset (M+1, M+2, ...)." Compute the offset as (YEAR(order) - YEAR(signup)) * 12 + MONTH(order) - MONTH(signup), then pivot with COUNT(DISTINCT CASE WHEN offset = k THEN user_id END).
Part 4 — 90-Day ARPU by Channel
WITH rev_90 AS (
SELECT s.channel,
s.user_id,
COALESCE(SUM(o.amount), 0) AS revenue_90d
FROM signups s
LEFT JOIN orders o
ON o.user_id = s.user_id
AND o.order_date >= s.signup_date
AND o.order_date < s.signup_date + INTERVAL '90 days'
-- Optionally restrict to fully matured users:
-- WHERE s.signup_date <= CURRENT_DATE - INTERVAL '90 days'
GROUP BY s.channel, s.user_id
),
channel_arpu AS (
SELECT channel,
COUNT(*) AS total_users,
SUM(revenue_90d) AS total_revenue_90d,
AVG(revenue_90d) AS arpu_90d
FROM rev_90
GROUP BY channel
)
SELECT *,
RANK() OVER (ORDER BY arpu_90d DESC) AS arpu_rank
FROM channel_arpu
ORDER BY arpu_rank;
Critical detail — filter placement. The date range belongs in the ON clause. Moving it to WHERE converts the LEFT JOIN into an inner join, silently dropping zero-revenue users and inflating ARPU. What you would actually be measuring is ARPPU (average revenue per paying user), which is a valid but different metric — flag this distinction in an interview.
Right-censoring. Users who signed up less than 90 days ago have incomplete observation windows and will drag their channel's ARPU down. The commented-out filter removes them. Decide based on whether you need a complete picture of all users or a fair comparison across channels.
On the sample data:
| Channel | User | Orders in window | 90-day revenue |
|---|---|---|---|
| organic | 101 | Jan 10 (day 5), Feb 5 (day 31) | 64.50 |
| paid_search | 102 | Feb 12 (day 37) | 60.00 |
| social_media | 103 | Mar 1 (day 52) | 30.00 |
Organic has the highest ARPU at 64.50.
Complexity
With A signup rows and T order rows, hash joins and hash aggregates run in roughly O(A + T). The window-function ranking steps add O(A log A) for the sort within each partition. Intermediate user-level results require O(A) space.
Edge Cases to Mention
- Zero-order users — always
LEFT JOIN+COALESCE(SUM(...), 0), never filter them out of denominators. - Duplicate signups — deduplicate to the earliest row before any analysis.
- Negative amounts (refunds) — ask whether to net, exclude, or cap at zero.
- Channels with very few users — a high ARPU on n = 3 is statistical noise; always show
total_usersnext to ARPU. - Ties in rankings — state your tie-breaking strategy before the interviewer asks.
- Timestamp vs. date boundaries —
order_date < signup_date + INTERVAL '90 days'behaves differently iforder_dateis a timestamp with a time component; cast consistently.
Python Sketch (Part 4)
import pandas as pd
def arpu_90d(signups: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
signups = signups.copy()
orders = orders.copy()
signups["signup_date"] = pd.to_datetime(signups["signup_date"])
orders["order_date"] = pd.to_datetime(orders["order_date"])
# Deduplicate signups to earliest row per user
signups = signups.sort_values("signup_date").drop_duplicates("user_id")
# Left-join and apply the 90-day window filter in the merge result
merged = signups.merge(orders, on="user_id", how="left")
delta = (merged["order_date"] - merged["signup_date"]).dt.days
in_window = (delta >= 0) & (delta < 90)
merged.loc[~in_window, "amount"] = 0 # zero out out-of-window orders
user_rev = merged.groupby(["channel", "user_id"])["amount"].sum().reset_index()
return (user_rev.groupby("channel")["amount"]
.agg(total_users="count", arpu_90d="mean")
.sort_values("arpu_90d", ascending=False)
.reset_index())
The same principles apply: keep every user in the denominator and zero out orders outside the window rather than dropping rows.