Ad Group Funnel Metrics with Below-Mean CTR Filter
SQL & DataModel answerLast updated
Write a single SQL query that computes cost, CTR, and conversion metrics per ad group, then returns only those with CTR below the unweighted average.
Ad Group Funnel Metrics with Below-Mean CTR Filter
You have an ad_groups table with one row per ad group:
| Column | Type | Meaning |
|---|---|---|
group_id | INTEGER | Unique ad group identifier |
group_name | VARCHAR | Ad group name |
launch_date | DATE | First day the group was active, inclusive |
close_date | DATE | Last day the group was active, inclusive |
daily_budget | DECIMAL | Fixed budget allocated per active day |
impressions | INTEGER | Total impressions recorded |
clicks | INTEGER | Total clicks recorded |
conversions | INTEGER | Total conversions recorded |
Work in PostgreSQL. Assume dates are inclusive, every row covers one complete ad group run, and daily_budget is constant throughout.
Task: Write a single query that returns only the ad groups whose click-through rate is strictly below the arithmetic mean of all valid ad-group-level click-through rates.
Columns to return:
group_idgroup_nametotal_cost—daily_budget× number of inclusive active daysctr—clicks / impressionsconversion_rate—conversions / clickscost_per_conversion—total_cost / conversions
Rules:
- Use decimal division throughout (not integer division).
- If a denominator is zero, return
NULLfor that metric instead of raising an error. - Ad groups with zero impressions have no valid CTR: they must not influence the average and cannot appear in the output.
- Sort the result by
group_idascending.
After writing the query, be ready to discuss whether total_cost reflects what was actually charged or something else.
Hints
Hint 1
Start by computing all per-row metrics in a first CTE, using NULLIF on every denominator. The average and the filter can come after, once the rates are already defined.
Hint 2
PostgreSQL date subtraction returns an integer count of days between two dates, not including the start. A campaign running on a single day produces 0 from subtraction, so you need to add 1 to get the inclusive count.
Hint 3
The problem asks for the mean of per-row CTRs, not SUM(clicks)/SUM(impressions). A window function AVG(ctr) OVER () over a derived table works cleanly here — but you cannot filter in the same SELECT level where a window function is computed, so you need an outer query.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The query breaks into three logical steps:
- Compute every per-row metric with safe division.
- Attach the benchmark — the unweighted average of valid CTRs — using a window function.
- Filter to rows strictly below that benchmark and sort.
Why unweighted average matters
"Arithmetic mean of campaign-level CTRs" means AVG(clicks / impressions) evaluated row by row, then averaged. That is not the same as SUM(clicks) / SUM(impressions), which is an impression-weighted pool. A large ad group with mediocre CTR would dominate the pooled version. Confusing the two is the most common mistake on this type of question — interviewers will probe for it.
The Query
WITH metrics AS (
SELECT
group_id,
group_name,
-- Inclusive day count: subtract dates, add 1
daily_budget * ((close_date - launch_date) + 1) AS total_cost,
-- Cast numerator to NUMERIC to force decimal division
clicks::NUMERIC / NULLIF(impressions, 0) AS ctr,
conversions::NUMERIC / NULLIF(clicks, 0) AS conversion_rate,
-- daily_budget is already DECIMAL, so no cast needed for cost
(daily_budget * ((close_date - launch_date) + 1))
/ NULLIF(conversions, 0) AS cost_per_conversion
FROM ad_groups
),
with_benchmark AS (
SELECT
m.*,
-- AVG automatically skips NULLs, so zero-impression rows don't count
AVG(ctr) OVER () AS avg_ctr
FROM metrics m
)
SELECT
group_id,
group_name,
total_cost,
ctr,
conversion_rate,
cost_per_conversion
FROM with_benchmark
WHERE ctr < avg_ctr -- NULL < x evaluates to NULL, so zero-impression rows drop out
ORDER BY group_id;
A scalar subquery in the WHERE clause is an equally valid alternative:
WHERE ctr < (SELECT AVG(ctr) FROM metrics)
Both produce identical results. The scalar subquery is often easier to read; the window-function version avoids the second scan of metrics if the planner doesn't cache the CTE.
Why Each Decision Is Correct
Inclusive day count. In PostgreSQL, date - date gives the number of days between the two dates, which equals zero for a single-day run. Adding 1 converts that to an inclusive count. Omitting it silently underestimates every cost.
Decimal division. Dividing two integers in PostgreSQL produces integer (truncated) division. Casting the numerator to NUMERIC promotes the result to exact decimal arithmetic. daily_budget is already DECIMAL, so cost math is fine without a cast.
NULLIF for zero denominators. NULLIF(x, 0) returns NULL when x is zero, and division by NULL yields NULL rather than an error. This handles impressions, clicks, and conversions uniformly.
Why two CTEs are required. Window functions are computed after WHERE in the same query level. Writing WHERE ctr < AVG(ctr) OVER () in a single SELECT is not legal — the window result isn't available to the filter yet. Materializing it in with_benchmark and filtering in the outer query is the correct structure. (HAVING ctr < AVG(ctr) without GROUP BY collapses the whole table to one row, which is wrong.)
Strict less-than. "Below the mean" is <. A row exactly at the mean is excluded. Using <= here is a logic error.
Complexity
- Time: O(n) to scan and compute metrics, one more O(n) pass for the window aggregate, O(n log n) for the final sort (or O(n) if the planner can use a primary-key index on
group_id). - Space: O(n) for the intermediate materialization the window needs, plus sort buffer.
Edge Cases
| Scenario | Result |
|---|---|
impressions = 0 | ctr is NULL — excluded from the average and from output |
clicks = 0, impressions > 0 | ctr = 0.0 — counts toward the mean, likely falls below it; conversion_rate is NULL |
conversions = 0 | cost_per_conversion is NULL; row can still appear in output |
| All rows have equal CTR | Nothing is strictly below the mean — empty result set |
| Every row has zero impressions | avg_ctr is NULL — WHERE NULL < NULL is NULL, result is empty |
close_date < launch_date (bad data) | Day count goes negative. Guard with GREATEST(..., 1) or surface it as a data quality issue |
Do not round intermediate values before comparing against the average. Rounding first can flip a borderline row the wrong direction. Apply rounding only to final display columns if presentation requires it.
Follow-up: Is total_cost What Was Actually Charged?
No — it is the planned budget, not actual spend. Several real-world factors break the equivalence:
- Under-delivery. Narrow audiences, low bids, or limited auction inventory can leave daily budget unspent. For niche ad groups this gap can be large.
- Over-delivery. Some platforms allow spend to exceed the daily cap on high-traffic days as long as the period total stays within bounds.
- Mid-flight changes. Pauses, budget edits, or targeting changes during the run aren't captured by a single
daily_budgetfigure. - Billing model. Actual charges are driven by CPM or CPC events, not by the budget line.
The practical consequence: cost_per_conversion here is a budgeted CPA. For under-delivering groups it overstates the true CPA. A stronger data model joins to a daily spend fact table and aggregates SUM(actual_spend) instead. Budget utilization (actual / planned) is also worth tracking as a health signal alongside the funnel metrics.