Campaign Attribution: Define Metrics and Write SQL for Purchase Impact
SQL & DataModel answerLast updated
Design attributable, time-bounded conversion metrics for a marketing campaign and implement the SQL to measure, baseline, and diagnose them across a five-table schema.
Context
Your team ran an outreach campaign (P_launch) contacting users via email, push, and SMS. You have five tables and need to (a) define the right metrics, (b) compute them in SQL, (c) build a fair comparison group, (d) diagnose a sudden drop, and (e) guard against a common bias.
Schema
users(user_id INT, signup_date DATE, country STRING)
events(user_id INT, event_time TIMESTAMP, event_name STRING, product_id INT, device STRING)
purchases(order_id INT, user_id INT, order_time TIMESTAMP, amount DECIMAL(10,2), product_id INT)
marketing_contacts(contact_id INT, user_id INT, contact_time TIMESTAMP, channel STRING, campaign STRING)
products(product_id INT, category STRING, launched_at DATE)
<details>
<summary>Sample rows</summary>
users
| user_id | signup_date | country |
|---|---|---|
| 1 | 2025-07-15 | US |
| 2 | 2025-07-20 | US |
| 3 | 2025-07-25 | CA |
| 4 | 2025-08-01 | US |
| 5 | 2025-08-05 | IN |
| 6 | 2025-08-10 | US |
events
| user_id | event_time | event_name | product_id | device |
|---|---|---|---|---|
| 1 | 2025-08-11 09:00:00 | page_view | 101 | iOS |
| 1 | 2025-08-12 10:00:00 | add_to_cart | 101 | iOS |
| 1 | 2025-08-15 12:00:00 | purchase | 101 | iOS |
| 2 | 2025-08-18 14:00:00 | page_view | 102 | Web |
| 2 | 2025-08-19 16:00:00 | purchase | 102 | Web |
| 3 | 2025-08-20 11:30:00 | page_view | 101 | Android |
| 4 | 2025-08-21 09:15:00 | page_view | 101 | iOS |
| 4 | 2025-08-28 17:45:00 | purchase | 101 | iOS |
| 5 | 2025-08-22 08:05:00 | unsubscribe | NULL | Web |
| 6 | 2025-08-23 19:20:00 | add_to_cart | 102 | Android |
purchases
| order_id | user_id | order_time | amount | product_id |
|---|---|---|---|---|
| 5001 | 1 | 2025-08-15 12:00:00 | 199.99 | 101 |
| 5002 | 2 | 2025-08-19 16:00:00 | 49.99 | 102 |
| 5003 | 4 | 2025-08-28 17:45:00 | 129.00 | 101 |
| 5004 | 6 | 2025-08-25 20:10:00 | 59.00 | 102 |
marketing_contacts
| contact_id | user_id | contact_time | channel | campaign |
|---|---|---|---|---|
| 9001 | 1 | 2025-08-11 08:00:00 | P_launch | |
| 9002 | 2 | 2025-08-18 09:00:00 | push | P_launch |
| 9003 | 4 | 2025-08-21 09:00:00 | P_launch | |
| 9004 | 6 | 2025-08-23 09:00:00 | sms | P_launch |
products
| product_id | category | launched_at |
|---|---|---|
| 101 | Elec | 2025-07-01 |
| 102 | Apparel | 2025-08-01 |
Tasks
A — Metric definitions
Define a primary success metric that is attributable to a single exposure, bounded to a fixed post-contact window, and robust to a small number of heavy buyers inflating the result. Add two guardrail metrics: one that captures negative user experience quickly, and one that signals delivery or landing-page problems well before the primary metric moves. Write precise formulas for all three.
B — Weekly conversion and revenue by country
Write SQL to compute, for each calendar week of first contact and each country:
- 14-day post-contact purchase conversion rate
- Average revenue per contacted user over the same window
Rules: use only each user's first contact in the campaign; exclude any purchase that happened strictly before that contact; exclude cohorts whose 14-day window has not yet closed relative to a watermark parameter :as_of_ts.
C — Matched non-contacted baseline
Write SQL that pairs each contacted user with exactly one non-contacted user who signed up in the same calendar week and the same country. Break ties deterministically by picking the smallest user_id. Compute the 14-day purchase rate for the matched non-contacted users using the same contact-time anchor as their paired contacted user.
D — Root-cause breakdown for a conversion drop
On 2025-08-20, the 14-day conversion rate for US contacted users falls roughly 20 percentage points below its prior 7-day average. Write SQL that produces a breakdown table sliced by device and product_id for users contacted on 2025-08-20, showing:
count_contactedconv_14dfor that dayconv_14d_prior(average over the preceding 7 days, same slice)delta(today minus prior)approx_contribution(approximate share of the total drop:count_contacted × delta)
Return only the top 3 slices by absolute contribution to the drop.
E — Unsubscribe bias check
In one or two sentences, describe one SQL or pipeline check you would add to confirm that users who unsubscribed immediately after being contacted are not silently distorting your conversion numbers.
What is expected: written metric formulas for part A, working SQL for parts B–D, and a concise written answer for part E. Explain any non-obvious choices (join order, maturity filter, revenue source).
Hints
Hint 1
For part A, a binary per-user flag (converted: yes/no) is more robust to outliers than summing revenue directly as the primary metric — a handful of high-value orders can swing a ratio wildly. Revenue belongs in a secondary metric with users in the denominator, not orders.
Hint 2
For part B, aggregate purchases per user before joining to dimension tables like users. Joining first and then aggregating risks row multiplication if any join key is not unique, silently inflating both conversion counts and revenue.
Hint 3
For part D, contribution to the drop is proportional to both the size of the slice and how far that slice's rate moved. A slice with a large count and a moderate delta can matter more than a small slice with a dramatic delta — so rank by count × delta, not by delta alone.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and key principles
Four things are being tested simultaneously: attribution discipline (tie each outcome to one exposure), window hygiene (exclude pre-contact purchases, filter immature cohorts), join safety (no fan-out, single revenue source), and causal reasoning (a fair baseline, a structured anomaly decomposition).
A) Metric definitions
Primary: 14-day post-contact binary conversion rate, first-contact only
Let t_u be the timestamp of user u's first contact in the campaign, and T be the data watermark. A cohort is mature when t_u + 14d ≤ T.
conv_14d = |{u : ∃ purchase p where t_u ≤ p.order_time < t_u + 14d}|
─────────────────────────────────────────────────────────
|{u contacted in campaign, mature}|
Why binary: one whale buyer does not move the metric. Why first contact: repeat touches should not get double attribution credit. Why half-open interval (≥ t_u, < t_u + 14d): purchases at exactly t_u are included; be explicit and consistent.
Guardrail 1: 3-day unsubscribe rate
unsub_3d = |{u : ∃ unsubscribe event where t_u ≤ e.event_time < t_u + 3d}|
────────────────────────────────────────────────────────────────
|{u contacted}|
Catches negative channel experience fast. If this spikes, pause the campaign before the 14-day window closes.
Guardrail 2: 24-hour engagement rate
eng_24h = |{u : ∃ page_view or add_to_cart event where t_u ≤ e.event_time < t_u + 24h}|
──────────────────────────────────────────────────────────────────────────────
|{u contacted}|
Pair with median time-to-first-engagement. A sudden collapse here indicates a delivery failure or broken landing page — visible days before conv_14d can react.
B) Weekly conversion and ARPCU by country
WITH first_contact AS (
-- Deduplicate to one row per user: earliest contact in the campaign
SELECT user_id, contact_time
FROM (
SELECT user_id,
contact_time,
ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY contact_time, contact_id -- deterministic tie-break
) AS rn
FROM marketing_contacts
WHERE campaign = 'P_launch'
) t
WHERE rn = 1
),
user_outcomes AS (
-- Aggregate purchases per user BEFORE joining to users; prevents fan-out
SELECT
fc.user_id,
fc.contact_time,
MAX(CASE WHEN p.order_id IS NOT NULL THEN 1 ELSE 0 END) AS converted,
COALESCE(SUM(p.amount), 0) AS revenue_14d
FROM first_contact fc
LEFT JOIN purchases p
ON p.user_id = fc.user_id
AND p.order_time >= fc.contact_time
AND p.order_time < fc.contact_time + INTERVAL '14 days'
GROUP BY fc.user_id, fc.contact_time
)
SELECT
CAST(DATE_TRUNC('week', o.contact_time) AS DATE) AS contact_week,
u.country,
COUNT(*) AS contacted_users,
AVG(o.converted) AS conv_14d,
AVG(o.revenue_14d) AS arpcu_14d
FROM user_outcomes o
JOIN users u ON u.user_id = o.user_id
-- Exclude cohorts whose 14-day window is still open
WHERE o.contact_time + INTERVAL '14 days' <= :as_of_ts
GROUP BY 1, 2
ORDER BY 1, 2;
Two critical choices: revenue comes from purchases only (joining events as well would double-count, since purchase events exist in both tables), and the maturity filter prevents the most recent weeks from appearing artificially low.
C) Matched non-contacted baseline
WITH first_contact AS (
SELECT user_id, contact_time
FROM (
SELECT user_id, contact_time,
ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY contact_time, contact_id
) AS rn
FROM marketing_contacts WHERE campaign = 'P_launch'
) t WHERE rn = 1
),
contacted_ids AS (
SELECT DISTINCT user_id FROM first_contact
),
non_contacted AS (
SELECT u.user_id,
DATE_TRUNC('week', u.signup_date) AS signup_week,
u.country
FROM users u
WHERE u.user_id NOT IN (SELECT user_id FROM contacted_ids)
),
contacted_with_dim AS (
SELECT fc.user_id,
fc.contact_time,
DATE_TRUNC('week', u.signup_date) AS signup_week,
u.country
FROM first_contact fc
JOIN users u ON u.user_id = fc.user_id
),
matched AS (
-- For each contacted user, pick the non-contacted user with the smallest
-- user_id in the same signup_week and country
SELECT
c.user_id AS contacted_user_id,
c.contact_time AS anchor_time,
MIN(nc.user_id) AS matched_user_id -- deterministic smallest-id tie-break
FROM contacted_with_dim c
JOIN non_contacted nc
ON nc.signup_week = c.signup_week
AND nc.country = c.country
GROUP BY c.user_id, c.contact_time
)
SELECT
COUNT(*) AS matched_pairs,
AVG(CASE WHEN p.order_id IS NOT NULL THEN 1.0 ELSE 0 END) AS baseline_conv_14d
FROM matched m
LEFT JOIN purchases p
ON p.user_id = m.matched_user_id
AND p.order_time >= m.anchor_time
AND p.order_time < m.anchor_time + INTERVAL '14 days'
;
The non-contacted user's 14-day window is anchored to the contacted user's contact_time. This ensures both groups face the same calendar window — a common mistake is anchoring the baseline to signup date instead.
D) Drop breakdown by device and product
WITH first_contact AS (
SELECT user_id, contact_time
FROM (
SELECT user_id, contact_time,
ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY contact_time, contact_id
) AS rn
FROM marketing_contacts WHERE campaign = 'P_launch'
) t WHERE rn = 1
),
fc_us AS (
-- US contacted users only, with device and product from their first event after contact
SELECT fc.user_id, fc.contact_time,
e.device,
e.product_id,
CAST(DATE(fc.contact_time) AS DATE) AS contact_date
FROM first_contact fc
JOIN users u ON u.user_id = fc.user_id AND u.country = 'US'
JOIN events e ON e.user_id = fc.user_id -- first post-contact event carries device/product context
AND e.event_time >= fc.contact_time
QUALIFY ROW_NUMBER() OVER (
PARTITION BY fc.user_id ORDER BY e.event_time
) = 1
),
outcomes AS (
SELECT fc.user_id, fc.contact_date, fc.device, fc.product_id,
MAX(CASE WHEN p.order_id IS NOT NULL THEN 1 ELSE 0 END) AS converted
FROM fc_us fc
LEFT JOIN purchases p
ON p.user_id = fc.user_id
AND p.order_time >= fc.contact_time
AND p.order_time < fc.contact_time + INTERVAL '14 days'
GROUP BY fc.user_id, fc.contact_date, fc.device, fc.product_id
),
slices AS (
SELECT contact_date, device, product_id,
COUNT(*) AS count_contacted,
AVG(converted) AS conv_14d
FROM outcomes
GROUP BY 1, 2, 3
),
prior AS (
SELECT device, product_id,
AVG(conv_14d) AS conv_14d_prior
FROM slices
WHERE contact_date >= DATE '2025-08-13'
AND contact_date < DATE '2025-08-20'
GROUP BY 1, 2
)
SELECT
s.device,
s.product_id,
s.count_contacted,
s.conv_14d,
p.conv_14d_prior,
s.conv_14d - p.conv_14d_prior AS delta,
s.count_contacted * (s.conv_14d - p.conv_14d_prior) AS approx_contribution
FROM slices s
JOIN prior p
ON p.device = s.device
AND p.product_id = s.product_id
WHERE s.contact_date = DATE '2025-08-20'
ORDER BY ABS(approx_contribution) DESC
LIMIT 3;
Contribution is count × delta rather than delta alone — a slice with 1,000 users and a −5 pp shift contributes far more to the aggregate drop than a slice of 10 users with a −30 pp shift.
E) Unsubscribe bias check
After computing conv_14d, left-join each contacted user to their unsubscribe events and flag users who unsubscribed within, say, 24 hours of contact. Report conv_14d separately for the flagged and unflagged groups. If the flagged group's conversion rate is meaningfully different, their inclusion is tilting the headline number — and depending on product intent, they should probably be excluded from the denominator entirely.
Common mistakes to avoid
- Joining
purchasesandeventsfor revenue and counting both — instant double-count. - Forgetting the maturity filter in part B — the most recent cohort always looks worse if its window is still open.
- Anchoring the baseline group's window to signup date instead of the paired user's contact time.
- Ranking the drop breakdown by
deltainstead ofcount × delta— small noisy slices bubble to the top.