Last-Touch Ad Attribution: Daily Campaign Conversion Report
SQL & DataModel answerLast updated
Write a SQL query that credits each conversion to the latest eligible ad impression within a 7-day lookback, then reports daily campaign metrics for January 2024.
Daily campaign performance with last-touch attribution
An advertising platform logs ad exposures and downstream purchases in two tables.
ad_impressions
| Column | Type | Meaning |
|---|---|---|
impression_id | STRING | Primary key for the exposure |
user_id | STRING | Viewer |
ad_id | STRING | Ad that was displayed |
campaign_id | STRING | Campaign owning the ad |
impression_ts | TIMESTAMP | Serve time (UTC) |
cost_usd | NUMERIC | Cost charged to the advertiser for this exposure |
ad_conversions
| Column | Type | Meaning |
|---|---|---|
conversion_id | STRING | Primary key for the conversion |
user_id | STRING | Converting user |
ad_id | STRING | Ad linked to the conversion |
conversion_ts | TIMESTAMP | Conversion time (UTC) |
revenue_usd | NUMERIC | Value of the conversion |
Attribution rules
- A conversion may only be credited to an impression with the same
user_idand the samead_id. - The impression must happen strictly before the conversion.
- The conversion must happen no later than 7 days after the impression.
- When several impressions qualify, credit the one closest in time before the conversion (the latest qualifying one).
- A conversion is credited at most once, and may end up credited to nothing.
Task
Consider only impressions served from 2024-01-01 00:00:00 UTC to 2024-01-31 23:59:59 UTC. For each campaign_id and UTC calendar date impression_date, return:
campaign_idimpression_dateimpressions: count of impressionsunique_impression_users: count of distinct users who saw an impressionattributed_conversions: conversions credited to those impressionsconversion_rate:attributed_conversions / impressionstotal_spend_usd: sum ofcost_usdtotal_conversion_revenue_usd: sum of revenue from the credited conversionsavg_hours_to_conversion: mean number of hours from impression to credited conversion, computed over credited conversions only
Campaign-days that have impressions but no credited conversions must still appear, with 0 conversions and 0 revenue.
Explain your approach, state any assumptions about boundaries and NULLs, and give the query.
Hints
Hint 1
Split the work in two: first decide which impression (if any) each conversion belongs to, then roll up January impressions by campaign and day.
Hint 2
Do not restrict impressions to January while choosing the winning impression. A December or February impression can be closer to the conversion and must be allowed to win; filter to January only after the winner is chosen.
Hint 3
Rank the eligible (conversion, impression) pairs per conversion by impression time descending and keep rank 1. Then collapse to one row per impression before joining back, so cost and impression counts are not multiplied by the number of conversions.
Hint 4
For the average, divide total hours by total credited conversions rather than averaging per-impression averages, and return NULL when there are no conversions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has two stages, and most errors come from blending them.
- Attribution: for every conversion, find the single latest impression that satisfies the eligibility rules (or none).
- Reporting: group the January impressions by campaign and date and attach whatever conversions were credited to them.
Two traps
Trap 1: filtering impressions too early. Imagine a user sees an ad on Jan 31 and again on Feb 1, then converts on Feb 2. The conversion belongs to the Feb 1 impression, so the Jan 31 impression gets nothing. If you limit impressions to January before ranking, the Jan 31 impression wrongly wins. The same applies to a late-December impression that beats earlier January ones. So rank among all impressions, and apply the January filter only when reporting.
Trap 2: fan-out. One impression can be credited with several conversions, because each conversion picks one impression but not the other way round. If you left-join raw conversions onto impressions and then run COUNT(*) or SUM(cost_usd), impressions and spend are inflated. Collapse the credited conversions to one row per impression first.
Query (PostgreSQL)
WITH eligible AS (
-- All (conversion, impression) pairs that satisfy rules 1-3,
-- ranked so the closest preceding impression gets rank 1.
SELECT
c.conversion_id,
c.conversion_ts,
c.revenue_usd,
i.impression_id,
i.impression_ts,
ROW_NUMBER() OVER (
PARTITION BY c.conversion_id
ORDER BY i.impression_ts DESC, i.impression_id DESC
) AS closeness_rank
FROM ad_conversions AS c
JOIN ad_impressions AS i
ON i.user_id = c.user_id
AND i.ad_id = c.ad_id
AND i.impression_ts < c.conversion_ts
AND c.conversion_ts <= i.impression_ts + INTERVAL '7 days'
-- Prune conversions that cannot belong to a January impression.
-- Impressions themselves are deliberately NOT filtered here.
WHERE c.conversion_ts > TIMESTAMP '2024-01-01 00:00:00'
AND c.conversion_ts < TIMESTAMP '2024-02-08 00:00:00'
),
winners AS (
SELECT * FROM eligible WHERE closeness_rank = 1
),
per_impression AS (
-- One row per impression that received at least one conversion.
SELECT
impression_id,
COUNT(*) AS conv_cnt,
SUM(COALESCE(revenue_usd, 0)) AS conv_revenue,
SUM(EXTRACT(EPOCH FROM (conversion_ts - impression_ts))) / 3600.0 AS hours_total
FROM winners
GROUP BY impression_id
),
january AS (
SELECT *
FROM ad_impressions
WHERE impression_ts >= TIMESTAMP '2024-01-01 00:00:00'
AND impression_ts < TIMESTAMP '2024-02-01 00:00:00'
)
SELECT
j.campaign_id,
CAST(j.impression_ts AS DATE) AS impression_date,
COUNT(*) AS impressions,
COUNT(DISTINCT j.user_id) AS unique_impression_users,
COALESCE(SUM(p.conv_cnt), 0) AS attributed_conversions,
COALESCE(SUM(p.conv_cnt), 0)::NUMERIC / COUNT(*) AS conversion_rate,
SUM(j.cost_usd) AS total_spend_usd,
COALESCE(SUM(p.conv_revenue), 0) AS total_conversion_revenue_usd,
SUM(p.hours_total) / NULLIF(SUM(p.conv_cnt), 0) AS avg_hours_to_conversion
FROM january AS j
LEFT JOIN per_impression AS p
ON p.impression_id = j.impression_id
GROUP BY j.campaign_id, CAST(j.impression_ts AS DATE)
ORDER BY j.campaign_id, impression_date;
Why this is correct
- Eligibility: the join predicate encodes same user, same ad, impression strictly earlier, and conversion at most 7 days later. A conversion with no matching impression produces no pair, so it is simply uncredited.
- Latest eligible impression:
ROW_NUMBER()partitioned by conversion and ordered by impression time descending picks the closest one. Keeping rank 1 guarantees at most one credit per conversion. - Deterministic ties: if two impressions share a timestamp for the same user and ad, the secondary sort on
impression_idmakes the choice repeatable. State this tie-break as an assumption. - Safe pruning: the latest possible January impression is just before Feb 1, plus 7 days gives just before Feb 8. Conversions outside
(Jan 1, Feb 8)cannot land on a January impression, so dropping them changes nothing and saves work. - No fan-out:
per_impressionhas one row per impression, so the left join keeps exactly one row per January impression.COUNT(*),COUNT(DISTINCT user_id)andSUM(cost_usd)stay exact. - Zero-conversion rows: the left join retains them, and
COALESCEconverts NULL counts and revenue to 0. The rate is 0 in that case. - Weighted average: dividing total hours by total conversions averages over conversions. Averaging per-impression averages would over-weight impressions with a single conversion. With no conversions the value is NULL, which is more honest than 0; mention that you chose this deliberately.
Complexity
Let C be the number of conversions in the window and k the typical number of impressions per (user, ad) within a 7-day lookback.
- Attribution join: O(C·k) candidate pairs.
- Ranking sort: O(C·k log k).
- Final aggregation: O(I) over January impressions, plus hashing for the distinct-user count.
An index or clustering on ad_impressions(user_id, ad_id, impression_ts) makes the range join cheap. In Spark or Presto, partition pruning on timestamps plays the same role. Memory is O(C·k) for candidate pairs.
Edge cases to mention
- Same-instant conversion: a conversion at exactly the impression time is not eligible (strict
<). - Exactly 7 days: included under the stated rule (
<=). If the business wanted it excluded, change one operator. - Boundary of the month: I use a half-open range
< Feb 1instead of<= 23:59:59, so sub-second timestamps on Jan 31 are not lost. - Time zones: both tables are UTC, so
CAST(... AS DATE)yields the UTC date. In a session with another time zone, convert explicitly. - NULL revenue: treated as 0 in the sum.
- Duplicate conversion rows: conversion_id is a primary key, so none expected; otherwise dedupe first.
Common mistakes
- Filtering impressions to January before ranking, which steals credit from later impressions.
- Joining conversions straight onto impressions and then summing cost, inflating spend.
- Using an inner join and silently dropping zero-conversion campaign-days.
- Averaging per-impression averages, or using
AVGover a joined table that includes NULL rows incorrectly. - Forgetting a tie-break, leading to non-reproducible results.
- Integer division when computing the rate.