Weekly Ad Click Rate: Overall and Per Campaign Category
SQL & DataModel answerLast updated
Write SQL that deduplicates ad event logs, restricts them to a one-week UTC window, and computes click-through rate overall and per campaign type, with safe handling of zero impressions.
Weekly ad click rate
You work with an ad-serving event log and need to report click-through rate (CTR = clicks / impressions) for the most recent full week.
Treat today as 2025-09-01. The reporting window is 2025-08-25 00:00:00 through 2025-08-31 23:59:59 (UTC).
Tables
ad_events(ad_id INT, campaign_id INT, event STRING, view_id STRING, event_time TIMESTAMP)
The event column holds either 'impression' or 'click'.
campaigns(campaign_id INT, campaign_type STRING)
The campaign_type column holds either 'direct_response' or 'brand'.
Sample data
ad_events
| ad_id | campaign_id | event | view_id | event_time |
|---|---|---|---|---|
| 101 | 1 | impression | v1001 | 2025-08-28 10:00:00 |
| 101 | 1 | click | v1001 | 2025-08-28 10:00:05 |
| 102 | 2 | impression | v1002 | 2025-08-30 12:00:00 |
| 102 | 2 | impression | v1003 | 2025-08-30 12:05:00 |
| 103 | 2 | click | v1002 | 2025-08-30 12:00:07 |
| 104 | 3 | impression | v1004 | 2025-08-26 08:00:00 |
campaigns
| campaign_id | campaign_type |
|---|---|
| 1 | direct_response |
| 2 | brand |
| 3 | direct_response |
Tasks
- Overall CTR. Return a single row with one column,
overall_ctr, for events inside the window. - CTR by campaign type. Return one row per
campaign_typewith columnscampaign_type,clicks,impressions,ctr.
Rules
- Only count events inside the window.
- Repeated log rows with the same
(ad_id, view_id, event)count once. - If a group has zero impressions,
ctrmust be0.0(no NULL, no division error). - Make sure integer division does not silently truncate the result.
Write the SQL (any common dialect is fine, so state which one you use), explain how you chose the window bounds and the output grain, and mention any edge cases you would raise with a stakeholder.
Hints
Hint 1
Use a half-open time interval: `event_time >= '2025-08-25'` and `event_time < '2025-09-01'`. This avoids any dependence on timestamp precision at 23:59:59.
Hint 2
Deduplicate after filtering by time, then count both event kinds in one pass with `COUNT(CASE WHEN event = 'click' THEN 1 END)` and the same for impressions.
Hint 3
For the per-type report, the output grain is `campaign_type`, not `campaign_id`. Join to `campaigns` first and group by type, otherwise `direct_response` will appear twice. Cast to a floating-point type before dividing and guard with a CASE for zero impressions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both queries follow the same three steps.
- Filter to the window. Use a half-open interval,
event_time >= '2025-08-25 00:00:00' AND event_time < '2025-09-01 00:00:00'. It covers all of Aug 25 to Aug 31 in UTC, including fractional seconds after 23:59:59, and has no off-by-one at midnight. Be careful with bounds like< '2025-09-01 24:00:00': depending on the engine it either fails to parse or means Sept 2 00:00, which pulls in all of Sept 1. - Deduplicate.
SELECT DISTINCT ad_id, campaign_id, view_id, eventcollapses repeated logs.campaign_idis carried along but is functionally determined byad_id, so it does not change the dedup grain. Dedup runs after the time filter so duplicates outside the window cannot influence the result. - Aggregate with conditional counts. One pass computes clicks and impressions. Then divide with an explicit cast and a zero guard.
Q1: overall CTR
WITH dedup AS (
SELECT DISTINCT ad_id, campaign_id, view_id, event
FROM ad_events
WHERE event_time >= TIMESTAMP '2025-08-25 00:00:00'
AND event_time < TIMESTAMP '2025-09-01 00:00:00'
AND event IN ('impression', 'click')
),
totals AS (
SELECT
COUNT(CASE WHEN event = 'click' THEN 1 END) AS clicks,
COUNT(CASE WHEN event = 'impression' THEN 1 END) AS impressions
FROM dedup
)
SELECT
CASE WHEN impressions = 0 THEN 0.0
ELSE CAST(clicks AS DOUBLE) / impressions
END AS overall_ctr
FROM totals;
COUNT(CASE ... THEN 1 END) returns 0 on an empty set, whereas SUM(CASE ...) would return NULL. The aggregate without GROUP BY always yields exactly one row, so the single-row requirement holds even with no data.
Q2: CTR by campaign type
WITH dedup AS (
SELECT DISTINCT ad_id, campaign_id, view_id, event
FROM ad_events
WHERE event_time >= TIMESTAMP '2025-08-25 00:00:00'
AND event_time < TIMESTAMP '2025-09-01 00:00:00'
AND event IN ('impression', 'click')
),
agg AS (
SELECT
c.campaign_type,
COUNT(CASE WHEN d.event = 'click' THEN 1 END) AS clicks,
COUNT(CASE WHEN d.event = 'impression' THEN 1 END) AS impressions
FROM campaigns c
LEFT JOIN dedup d ON d.campaign_id = c.campaign_id
GROUP BY c.campaign_type
)
SELECT
campaign_type,
clicks,
impressions,
CASE WHEN impressions = 0 THEN 0.0
ELSE CAST(clicks AS DOUBLE) / impressions
END AS ctr
FROM agg
ORDER BY campaign_type;
Driving from campaigns with a LEFT JOIN means a type with no traffic still shows up with 0, 0, 0.0. Grouping by campaign_type directly (not by campaign_id first) guarantees one row per type.
Verification on the sample
| Scope | Impressions | Clicks | CTR |
|---|---|---|---|
| Overall | 4 (v1001, v1002, v1003, v1004) | 2 | 0.5 |
| brand | 2 | 1 | 0.5 |
| direct_response | 2 | 1 | 0.5 |
If you grouped by campaign_id and then joined to campaigns, direct_response would appear twice (campaign 1 with CTR 1.0, campaign 3 with 0.0). That is the classic grain bug.
Complexity
- Time: O(N) to scan and filter, plus a hash aggregate for the DISTINCT, roughly O(N) expected. On a distributed engine this adds a shuffle on the dedup key. The join to
campaignsis cheap because that table is small and is typically broadcast. - Space: O(D), where D is the number of distinct
(ad_id, view_id, event)rows in the window. - Scale: partition
ad_eventsby date so the window filter prunes partitions rather than scanning everything.
Common mistakes
- Wrong upper bound (
24:00:00, or<= '2025-08-31 23:59:59'which drops sub-second events). - Integer division:
clicks / impressionsreturns 0 in Postgres, SQL Server and Presto when both are integers. - Grouping at the wrong grain in Q2.
- Using
SUMinstead ofCOUNTon conditional expressions and getting NULLs on empty input. - Deduplicating before the time filter, or deduplicating on fewer columns than specified, which merges a click with its impression.
Edge cases to raise
- Zero impressions: return 0.0, as specified.
- Events with a
campaign_idmissing fromcampaigns: they count in Q1 but vanish from Q2, so per-type totals will not sum to the overall total. To reconcile, LEFT JOIN fromdedupand bucket withCOALESCE(c.campaign_type, 'unknown'). - Clicks with no matching impression: click
(103, v1002)has no impression for ad 103. The spec defines CTR as raw clicks over impressions, so it counts. A stricter attributed CTR would only count clicks that join to an impression on the same(ad_id, view_id), which guarantees CTR is at most 1.0. - NULL
view_id:DISTINCTtreats NULLs as equal, so all NULL-view logs for an ad and event collapse into one row. Confirm whether to keep or drop them. - Dirty event values such as
'Click': theINfilter excludes them. Normalize withLOWER(TRIM(event))if needed. - Timezone: if
event_timeis stored in local time, convert to UTC before filtering.
pandas equivalent
import pandas as pd
def ctr_reports(ad_events, campaigns):
start = pd.Timestamp("2025-08-25 00:00:00")
end = pd.Timestamp("2025-09-01 00:00:00") # exclusive
ev = ad_events[
(ad_events["event_time"] >= start)
& (ad_events["event_time"] < end)
& (ad_events["event"].isin(["impression", "click"]))
].drop_duplicates(subset=["ad_id", "view_id", "event"])
def safe_ctr(c, i):
return float(c) / i if i else 0.0
clicks = int((ev["event"] == "click").sum())
imps = int((ev["event"] == "impression").sum())
overall = safe_ctr(clicks, imps)
m = campaigns.merge(ev, on="campaign_id", how="left")
g = m.groupby("campaign_type").agg(
clicks=("event", lambda s: int((s == "click").sum())),
impressions=("event", lambda s: int((s == "impression").sum())),
).reset_index()
g["ctr"] = [safe_ctr(c, i) for c, i in zip(g["clicks"], g["impressions"])]
return overall, g
The left merge keeps campaign types with no events (their event is NaN and counts as zero), mirroring the SQL.