Daily Spend Leaders and Cost-Efficiency by Campaign Goal
SQL & DataModel answerLast updated
Rank the top daily advertisers with ties, then compute cost per KPI by goal using a launch-date filter and safe division.
You work on a team that tracks paid advertising performance. Three tables capture spend, conversion outcomes, and campaign metadata.
Table: campaign_spend
| Column | Type | Description |
|---|---|---|
date | DATE | UTC calendar date. |
advertiser_id | BIGINT | Unique advertiser identifier. |
campaign_id | BIGINT | Unique campaign identifier. |
creative_group | VARCHAR | Sub-grouping within a campaign. |
ad_spend | DECIMAL | Dollars spent on that row. |
impressions | BIGINT | Impressions served. |
Table: campaign_conversion
| Column | Type | Description |
|---|---|---|
date | DATE | UTC calendar date. |
advertiser_id | BIGINT | Unique advertiser identifier. |
campaign_id | BIGINT | Unique campaign identifier. |
creative_group | VARCHAR | Sub-grouping within a campaign. |
installs | BIGINT | Install count attributed to the campaign. |
kpi_cnt | BIGINT | Final KPI conversion count for the campaign's optimization goal. |
Table: campaign_goal
| Column | Type | Description |
|---|---|---|
campaign_id | BIGINT | Unique campaign identifier. |
campaign_goal | VARCHAR | Optimization goal (e.g., install, purchase, signup). |
campaign_launch_date | DATE | UTC date the campaign went live. |
Assumptions:
- Each
campaign_idmaps to exactly onecampaign_goal. - Spend and conversion rows share the grain (
date,advertiser_id,campaign_id,creative_group), but a row may exist in one table without a matching row in the other.
Write SQL to answer both of the following questions.
Part 1 — Top 3 advertisers by daily spend
Collapse spend to the (date, advertiser_id) level and rank advertisers within each day by total spend, highest first. Return every advertiser whose rank falls within the top 3, including all tied advertisers.
Required output columns: date, advertiser_id, daily_ad_spend, spend_rank.
Part 2 — Cost per KPI by campaign goal
For each campaign_goal, sum total ad spend and total KPI conversions across every campaign sharing that goal. Only include rows dated on or after the campaign's launch date. Divide total spend by total KPI count to produce cost_per_kpi; return NULL instead of dividing by zero when the KPI total is zero.
Required output columns: campaign_goal, total_ad_spend, total_kpi_cnt, cost_per_kpi.
Hints
Hint 1
Part 1: The source table has one row per campaign and creative, not per advertiser per day. Aggregate first, then apply your ranking function — you cannot rank raw rows. Think about which of ROW_NUMBER, RANK, and DENSE_RANK handles ties the way the problem requires.
Hint 2
Part 2: Spend and conversion data live in separate tables and may not have matching rows at every grain. A straight inner join will silently drop spend that has no corresponding conversion row, which understates cost. Consider stacking both tables with UNION ALL before joining to campaign_goal, or use a FULL OUTER JOIN on pre-aggregated CTEs.
Hint 3
For the launch-date filter in Part 2, apply it after joining to campaign_goal so each fact row is compared against its own campaign's launch date — not a fixed cutoff. For safe division, NULLIF(denominator, 0) turns a zero into NULL, making the whole expression NULL rather than throwing an error.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and common traps
Both parts are deceptively short to write but contain specific traps that separate a polished answer from a quick one.
- Part 1: you must aggregate before ranking, and you must choose a ranking function whose tie semantics match the spec.
- Part 2: two fact tables with potentially mismatched rows, a per-campaign date filter, and a division that must not blow up on zero.
State these assumptions before writing: which ranking function you chose and why, and how you handle rows that exist in one fact table but not the other.
Part 1: Top 3 advertisers by daily spend
Why aggregate first
campaign_spend is at the grain of (date, advertiser_id, campaign_id, creative_group). One advertiser may have dozens of rows on a single day. Ranking raw rows would produce a meaningless result — you need one row per advertiser per day before the window function runs.
Picking the right ranking function
Take this example for a single day: advertiser spend values of 500, 500, 300, 200.
| Function | Assigned ranks | Rows where rank ≤ 3 |
|---|---|---|
ROW_NUMBER | 1, 2, 3, 4 | 3 — tie broken arbitrarily, wrong |
RANK | 1, 1, 3, 4 | 3 |
DENSE_RANK | 1, 1, 2, 3 | 4 |
The spec says "return all advertisers tied within the top 3 ranks." That most naturally means the top 3 distinct rank values, so DENSE_RANK is the right choice here. If the interviewer meant "top 3 positions plus anyone tied at the boundary," RANK also works and returns the same set in this case. Raising that ambiguity out loud is itself a good signal.
WITH daily_spend AS (
SELECT
date,
advertiser_id,
SUM(ad_spend) AS daily_ad_spend
FROM campaign_spend
GROUP BY date, advertiser_id
),
ranked AS (
SELECT
date,
advertiser_id,
daily_ad_spend,
DENSE_RANK() OVER (
PARTITION BY date
ORDER BY daily_ad_spend DESC
) AS spend_rank
FROM daily_spend
)
SELECT date, advertiser_id, daily_ad_spend, spend_rank
FROM ranked
WHERE spend_rank <= 3
ORDER BY date, spend_rank, advertiser_id;
Window functions are evaluated after GROUP BY and before the outer WHERE, which is why the <= 3 filter must live in a wrapping query — you cannot filter on a window function alias in the same SELECT.
Edge cases to mention:
- Fewer than 3 advertisers on a given day: all of them are returned, which is correct.
- NULL
ad_spend:SUMignores NULLs. Some engines sort NULLs first underDESC; useCOALESCE(SUM(ad_spend), 0)orORDER BY ... DESC NULLS LASTto be explicit.
Part 2: Cost per KPI by campaign goal
The join trap
The naive approach — campaign_spend INNER JOIN campaign_conversion on the four-column grain — has two problems:
- Silent row loss. Spend with no matching conversion row represents real cost with zero conversions. An inner join drops it, understating cost per KPI. Conversions without spend rows also vanish.
- Fan-out risk. If either table has duplicate rows at the grain (late-arriving data, restatements), the join multiplies counts from the other side.
The cleanest fix is to stack both tables with UNION ALL, putting a zero placeholder in whichever column the table doesn't own. That avoids any join cardinality issue entirely and works across all SQL dialects including MySQL, which lacks FULL OUTER JOIN.
WITH facts AS (
SELECT
campaign_id,
date,
COALESCE(ad_spend, 0) AS ad_spend,
0 AS kpi_cnt
FROM campaign_spend
UNION ALL
SELECT
campaign_id,
date,
0 AS ad_spend,
COALESCE(kpi_cnt, 0) AS kpi_cnt
FROM campaign_conversion
)
SELECT
g.campaign_goal,
SUM(f.ad_spend) AS total_ad_spend,
SUM(f.kpi_cnt) AS total_kpi_cnt,
SUM(f.ad_spend) * 1.0 / NULLIF(SUM(f.kpi_cnt), 0) AS cost_per_kpi
FROM facts f
JOIN campaign_goal g
ON f.campaign_id = g.campaign_id
WHERE f.date >= g.campaign_launch_date
GROUP BY g.campaign_goal
ORDER BY g.campaign_goal;
If the interviewer asks for a join-based alternative, pre-aggregate each side to the grain, then FULL OUTER JOIN and COALESCE the key columns:
WITH s AS (
SELECT date, advertiser_id, campaign_id, creative_group,
SUM(ad_spend) AS ad_spend
FROM campaign_spend
GROUP BY 1, 2, 3, 4
),
c AS (
SELECT date, advertiser_id, campaign_id, creative_group,
SUM(kpi_cnt) AS kpi_cnt
FROM campaign_conversion
GROUP BY 1, 2, 3, 4
),
joined AS (
SELECT
COALESCE(s.campaign_id, c.campaign_id) AS campaign_id,
COALESCE(s.date, c.date) AS date,
COALESCE(s.ad_spend, 0) AS ad_spend,
COALESCE(c.kpi_cnt, 0) AS kpi_cnt
FROM s
FULL OUTER JOIN c
ON s.date = c.date
AND s.advertiser_id = c.advertiser_id
AND s.campaign_id = c.campaign_id
AND s.creative_group = c.creative_group
)
SELECT
g.campaign_goal,
SUM(j.ad_spend) AS total_ad_spend,
SUM(j.kpi_cnt) AS total_kpi_cnt,
SUM(j.ad_spend) * 1.0 / NULLIF(SUM(j.kpi_cnt), 0) AS cost_per_kpi
FROM joined j
JOIN campaign_goal g ON j.campaign_id = g.campaign_id
WHERE j.date >= g.campaign_launch_date
GROUP BY g.campaign_goal;
Why each decision matters
- Launch-date filter applied after the goal join. Each fact row is compared against its own campaign's
campaign_launch_date. A common mistake applies a single hardcoded date or filters only one of the two fact tables. - Ratio of sums, not average of ratios.
cost_per_kpiis computed asSUM(spend) / SUM(kpi)after the full aggregation. Averaging per-campaign CPAs would weight a campaign spending $10 the same as one spending $10 million — almost always the wrong business interpretation. NULLIFfor safe division.NULLIF(SUM(kpi_cnt), 0)returns NULL when the denominator is zero, making the entire expression NULL rather than raising a division-by-zero error — exactly what the spec requires.* 1.0for decimal output. In engines that perform integer division when both operands are integers, multiplying by1.0forces a floating-point result. It's cheap and explicit.- No fan-out from the goal join. Because each
campaign_idmaps to exactly onecampaign_goal, joiningfactstocampaign_goalnever multiplies rows.