Single Funnel Score for Ads from Impression and Click Logs
SQL & DataModel answerLast updated
Design one metric that blends click-through and purchase quality, then write SQL that attributes clicks to impressions and reports it per ad for the past week.
Scoring ads from raw event logs
An in-app advertising system writes two event tables.
impressions has one row each time an ad is shown.
| user_id | ad_id | event_time | platform |
|---|---|---|---|
| 101 | 9001 | 2023-07-01 10:00:00 | iOS |
| 102 | 9002 | 2023-07-01 10:00:05 | Android |
| 101 | 9003 | 2023-07-01 10:00:10 | Web |
clicks_conversions has one row per click, with a flag showing whether that click ended in a purchase.
| user_id | ad_id | click_time | is_purchase |
|---|---|---|---|
| 101 | 9001 | 2023-07-01 10:00:02 | 0 |
| 102 | 9002 | 2023-07-01 10:00:06 | 1 |
| 103 | 9004 | 2023-07-01 10:00:12 | 0 |
Your task
- Propose one metric that reflects both how often an ad gets clicked and how well those clicks turn into purchases. Explain why you chose it and why it beats looking at click-through rate or conversion rate alone.
- Write a SQL query that joins the two tables and returns this metric per
ad_idfor the last 7 days.
What to cover
- The join keys and the timing rule that links a click to an impression.
- How you avoid counting a click twice when a user saw the same ad several times.
- What happens to clicks that have no matching impression, and to ads that were shown but never clicked.
- Division-by-zero safety and integer-division pitfalls.
- How you would treat ads with very few impressions.
- Optionally, the same logic in pandas.
Hints
Hint 1
Write the funnel as impressions -> clicks -> purchases. Think about what you get if you multiply the rate of the first step by the rate of the second.
Hint 2
Link a click to an impression using both user_id and ad_id, require the click to come after the impression, and cap the gap with an explicit attribution window. Then keep only the most recent qualifying impression per click.
Hint 3
Aggregate impressions and attributed clicks separately and LEFT JOIN from the impression side, so ads with zero clicks still appear. Use NULLIF for ratios and multiply by 1.0 to avoid integer division.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
The interviewer is checking three things: whether you can design a sensible single KPI, whether your join attributes clicks correctly, and whether you handle edge cases (orphan clicks, duplicates, zero denominators, the date filter).
The metric
The funnel has two standard rates:
- CTR = clicks / impressions, which shows how engaging the ad is.
- CVR = purchases / clicks, which shows the quality of the traffic.
Their product telescopes:
CTR x CVR = (clicks / impressions) x (purchases / clicks) = purchases / impressions
I would report purchases per 1,000 impressions (a conversions-per-mille figure) as the single score.
Why it works:
- A clickbait ad (high CTR, low CVR) scores low.
- An ad with a great CVR that almost nobody clicks also scores low.
- It measures the end-to-end rate at which ad inventory becomes value.
CTR and CVR should still appear next to it as diagnostics: the composite says which ads win, the components say why.
Low-volume caveat. An ad with 1 impression and 1 purchase would score 1000 and top the ranking. Mitigate with smoothing, for example (purchases + a) / (impressions + b) with a prior drawn from the global rate, or a minimum-impressions threshold, or a lower confidence bound.
Join design
- Keys:
user_idandad_id. A click belongs to an impression of the same ad shown to the same user. - Ordering:
click_time >= event_time. A click cannot precede its impression. - Attribution window: state one explicitly, e.g. 24 hours.
- De-duplication: if the user saw the ad several times, attribute the click to the most recent preceding impression, using
ROW_NUMBER() ... ORDER BY event_time DESCand keepingrn = 1. Otherwise one click would be counted once per matching impression and inflate clicks and purchases. - Orphan clicks (like user 103 / ad 9004 in the sample) have no impression, so an inner join drops them. This is intended, since they cannot be attributed.
- Zero-click ads: aggregate impressions separately and LEFT JOIN the click aggregate onto it, so ads that were shown but never clicked still appear with a score of 0.
- Last 7 days: filter impressions by
event_time. Ads are judged on the impressions served in the period.
SQL (PostgreSQL)
WITH imp AS (
SELECT user_id, ad_id, event_time
FROM impressions
WHERE event_time >= CURRENT_TIMESTAMP - INTERVAL '7 days'
AND event_time < CURRENT_TIMESTAMP
),
clk AS (
SELECT user_id, ad_id, click_time, is_purchase,
ROW_NUMBER() OVER (ORDER BY user_id, ad_id, click_time) AS click_id
FROM clicks_conversions
WHERE click_time >= CURRENT_TIMESTAMP - INTERVAL '7 days'
),
attributed AS (
SELECT c.click_id, c.ad_id, c.is_purchase,
ROW_NUMBER() OVER (PARTITION BY c.click_id
ORDER BY i.event_time DESC) AS rn
FROM clk c
JOIN imp i
ON i.user_id = c.user_id
AND i.ad_id = c.ad_id
AND c.click_time >= i.event_time
AND c.click_time <= i.event_time + INTERVAL '24 hours'
),
click_agg AS (
SELECT ad_id,
COUNT(*) AS clicks,
SUM(is_purchase) AS purchases
FROM attributed
WHERE rn = 1
GROUP BY ad_id
),
imp_agg AS (
SELECT ad_id, COUNT(*) AS impressions
FROM imp
GROUP BY ad_id
)
SELECT
ia.ad_id,
ia.impressions,
COALESCE(ca.clicks, 0) AS clicks,
COALESCE(ca.purchases, 0) AS purchases,
COALESCE(ca.clicks, 0) * 1.0 / ia.impressions AS ctr,
COALESCE(ca.purchases, 0) * 1.0 / NULLIF(ca.clicks, 0) AS cvr,
COALESCE(ca.purchases, 0) * 1000.0 / ia.impressions AS conversions_per_mille
FROM imp_agg ia
LEFT JOIN click_agg ca ON ca.ad_id = ia.ad_id
ORDER BY conversions_per_mille DESC, ia.impressions DESC;
Notes:
ia.impressionsis never 0 because it comes from an aggregate over existing rows.NULLIFmakes CVR NULL, not an error, for ads with no clicks.* 1.0avoids integer division.
Trace on the sample (assuming it falls in the window)
| ad_id | impressions | clicks | purchases | CTR | CVR | per 1,000 |
|---|---|---|---|---|---|---|
| 9001 | 1 | 1 | 0 | 1.0 | 0.0 | 0 |
| 9002 | 1 | 1 | 1 | 1.0 | 1.0 | 1000 |
| 9003 | 1 | 0 | 0 | 0.0 | NULL | 0 |
Ad 9004's click is excluded as unattributable.
pandas equivalent
merge_asof performs the "latest prior impression within a tolerance" join directly.
import pandas as pd
def ad_performance(impressions, clicks, now,
window=pd.Timedelta(hours=24)):
start = now - pd.Timedelta(days=7)
imp = impressions[(impressions.event_time >= start) &
(impressions.event_time < now)]
clk = clicks[clicks.click_time >= start].sort_values("click_time")
att = pd.merge_asof(
clk, imp.sort_values("event_time")[["user_id", "ad_id", "event_time"]],
left_on="click_time", right_on="event_time",
by=["user_id", "ad_id"], direction="backward", tolerance=window,
).dropna(subset=["event_time"])
click_agg = att.groupby("ad_id").agg(clicks=("is_purchase", "size"),
purchases=("is_purchase", "sum"))
out = (imp.groupby("ad_id").size().rename("impressions")
.to_frame().join(click_agg, how="left")
.fillna({"clicks": 0, "purchases": 0}))
out["ctr"] = out.clicks / out.impressions
out["cvr"] = out.purchases / out.clicks.where(out.clicks > 0)
out["per_mille"] = 1000 * out.purchases / out.impressions
return out.reset_index().sort_values(["per_mille", "impressions"],
ascending=False)
Complexity
With I impressions and C clicks in the window, the aggregations are O(I + C). The join is the dominant cost: with an index or sort on (user_id, ad_id, time) each click scans only the few impressions of that user and ad, giving roughly O((I + C) log(I + C)) for sorting plus the per-click candidate set. merge_asof is O(I log I + C log C) from sorting.
Common mistakes
- Joining on
ad_idonly, which attributes one user's click to another user's impression. - Skipping the dedup step, so repeated impressions multiply clicks.
- An inner join from impressions to clicks, which drops zero-click ads and inflates averages.
- Integer division producing 0 for every rate.
- Filtering on click time only, so the denominator and numerator cover different populations.
- Ranking raw rates without smoothing or a minimum-volume rule.
Possible follow-ups
- Break the metric down by platform, which only requires carrying
platformthrough the impression CTE. - Handle purchases that occur long after the click by separating click time from conversion time.
- Compare ads statistically rather than by point estimates, e.g. with a confidence interval on purchases per impression.