KatInterview

Ad Group Funnel Metrics with Below-Mean CTR Filter

SQL & DataModel answer
MediumModel answerSQL & Datasqlctewindow-functions

Last 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:

ColumnTypeMeaning
group_idINTEGERUnique ad group identifier
group_nameVARCHARAd group name
launch_dateDATEFirst day the group was active, inclusive
close_dateDATELast day the group was active, inclusive
daily_budgetDECIMALFixed budget allocated per active day
impressionsINTEGERTotal impressions recorded
clicksINTEGERTotal clicks recorded
conversionsINTEGERTotal 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_id
  • group_name
  • total_cost — daily_budget × number of inclusive active days
  • ctr — clicks / impressions
  • conversion_rate — conversions / clicks
  • cost_per_conversion — total_cost / conversions

Rules:

  • Use decimal division throughout (not integer division).
  • If a denominator is zero, return NULL for 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_id ascending.

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.