KatInterview

Weekly Ad Click Rate: Overall and Per Campaign Category

SQL & DataModel answer
MediumModel answerSQL & Datasqlaggregationdeduplication

Last 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_idcampaign_ideventview_idevent_time
1011impressionv10012025-08-28 10:00:00
1011clickv10012025-08-28 10:00:05
1022impressionv10022025-08-30 12:00:00
1022impressionv10032025-08-30 12:05:00
1032clickv10022025-08-30 12:00:07
1043impressionv10042025-08-26 08:00:00

campaigns

campaign_idcampaign_type
1direct_response
2brand
3direct_response

Tasks

  1. Overall CTR. Return a single row with one column, overall_ctr, for events inside the window.
  2. CTR by campaign type. Return one row per campaign_type with columns campaign_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, ctr must be 0.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.