Daily Top Spenders and Post-Launch Cost per KPI

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

An advertising platform logs daily media spend, daily attributed conversions, and campaign metadata across three relational tables: campaign_spend, campaign_conversion, and campaign_goal. Every campaign_id in campaign_goal maps to a single target outcome (campaign_goal) and a UTC go-live date (campaign_launch_date). Whenever spend and conversion records need to be matched at row level, their composite grain is (date, advertiser_id, campaign_id, creative_group).

Address the following two analytical SQL tasks:

  1. Daily top 3 advertisers by spend: Roll up ad_spend per (date, advertiser_id) and rank advertisers within each UTC day from largest to smallest daily expenditure. Retain all advertisers tied within the top 3 ranks and output date, advertiser_id, daily_ad_spend, spend_rank.
  2. Post-launch cost per KPI by campaign goal (graded QUERY deliverable): For each campaign_goal, compute total ad spend (total_ad_spend) and total target conversions (total_kpi_cnt, summed from kpi_cnt) across every campaign assigned to that goal, counting only rows dated on or after that specific campaign's campaign_launch_date (date >= campaign_launch_date). Calculate cost_per_kpi = total_ad_spend / total_kpi_cnt rounded to 4 decimal places, outputting NULL when total_kpi_cnt equals 0. Return campaign_goal, total_ad_spend, total_kpi_cnt, cost_per_kpi in any row order.

Graded output note: Set QUERY in solution.py to your Part 2 query (SQLite dialect). Part 1 is discussed in the interview follow-ups.

Input Schema

campaign_spend

Column Type Description
date DATE UTC calendar date (YYYY-MM-DD).
advertiser_id BIGINT Numeric identifier of the advertiser.
campaign_id BIGINT Numeric identifier of the campaign.
creative_group VARCHAR Creative group label inside the campaign.
ad_spend DECIMAL(12,2) Dollar expenditure recorded on this row.
impressions BIGINT Impression count served on this row.

campaign_conversion

Column Type Description
date DATE UTC calendar date (YYYY-MM-DD).
advertiser_id BIGINT Numeric identifier of the advertiser.
campaign_id BIGINT Numeric identifier of the campaign.
creative_group VARCHAR Creative group label inside the campaign.
installs BIGINT Attributed app install count (regardless of campaign goal).
kpi_cnt BIGINT Attributed count of the campaign's designated target KPI.

campaign_goal

Column Type Description
campaign_id BIGINT Unique campaign identifier.
campaign_goal VARCHAR Optimization objective (e.g., 'app_install', 'checkout', 'lead').
campaign_launch_date DATE Official UTC launch date of the campaign (YYYY-MM-DD).

Examples

Example 1

Input:

campaign_spend

date advertiser_id campaign_id creative_group ad_spend impressions
'2025-04-10' 10 501 'video' 45 900
'2025-04-11' 10 501 'video' 90 1800
'2025-04-11' 10 501 'banner' 30 600
'2025-04-10' 10 502 'video' 150 2500
'2025-04-11' 10 502 'video' 100 1700
'2025-04-10' 20 601 'banner' 75 1400
'2025-04-11' 20 601 'banner' 45 800
'2025-04-11' 20 602 'video' 25 450
'2025-04-12' 20 602 'video' 85 1300

campaign_conversion

date advertiser_id campaign_id creative_group installs kpi_cnt
'2025-04-10' 10 501 'video' 6 6
'2025-04-11' 10 501 'video' 11 11
'2025-04-11' 10 501 'banner' 4 4
'2025-04-10' 10 502 'video' 12 5
'2025-04-11' 10 502 'video' 8 4
'2025-04-10' 20 601 'banner' 5 5
'2025-04-11' 20 602 'video' 5 2
'2025-04-12' 20 602 'video' 9 0

campaign_goal

campaign_id campaign_goal campaign_launch_date
501 'app_install' '2025-04-11'
502 'checkout' '2025-04-10'
601 'app_install' '2025-04-10'
602 'lead' '2025-04-12'

Expected Output (Part 2 graded query):

campaign_goal total_ad_spend total_kpi_cnt cost_per_kpi
'app_install' 240 20 12.0
'checkout' 250 9 27.7778
'lead' 85 0 NULL

Explanation: - For 'app_install', campaign 501 drops pre-launch 2025-04-10 activity and contributes 90 + 30 = 120 spend and 11 + 4 = 15 KPIs; campaign 601 launches 2025-04-10 and contributes 75 + 45 = 120 spend (even though 2025-04-11 has no conversion row) and 5 KPIs, giving 240 / 20 = 12.0. - For 'checkout', campaign 502 contributes 150 + 100 = 250 spend and 5 + 4 = 9 target KPIs (kpi_cnt, not installs), giving 250 / 9 = 27.7778. - For 'lead', campaign 602 ignores pre-launch 2025-04-11 rows and records 85 spend with 0 KPIs on 2025-04-12, returning NULL for cost_per_kpi.

Constraints

  • Spend days may lack corresponding rows in campaign_conversion, conversion days may lack corresponding rows in campaign_spend, and either fact table may contain multiple rows sharing the same (date, advertiser_id, campaign_id, creative_group) key.
  • Rows belonging to a campaign_id absent from campaign_goal have no assigned goal and must be excluded.
  • Different campaigns under the same campaign_goal can have different campaign_launch_date values; filter every row against its own campaign's launch date (date >= campaign_launch_date).
  • Round non-NULL cost_per_kpi values to 4 decimal places; output row order is unrestricted.

Step-by-step walkthrough

  1. Understand the graded task and table schemas

    This prompt asks two SQL questions, and the automated grader evaluates Part 2: calculate cost per KPI for each campaign goal. (A complete SQL solution for Part 1—the top 3 spending advertisers per day with ties—is covered in the explanation's follow-up section.)

    Let's inspect the three tables:

    • campaign_spend(date, advertiser_id, campaign_id, creative_group, ad_spend, impressions): daily ad spend rows.
    • campaign_conversion(date, advertiser_id, campaign_id, creative_group, installs, kpi_cnt): daily conversion rows. Notice there are two count columns (installs and kpi_cnt)—always sum kpi_cnt, since that column tracks conversions for each campaign's actual target event!
    • campaign_goal(campaign_id, campaign_goal, campaign_launch_date): maps each campaign_id to its single campaign_goal (such as 'app_install', 'checkout', or 'lead') and its campaign_launch_date.

    Required output columns: campaign_goal, total_ad_spend, total_kpi_cnt, cost_per_kpi, obeying these rules:

    • Count spend and conversions only on or after each campaign's own campaign_launch_date (date >= campaign_launch_date).
    • Compute cost_per_kpi = total_ad_spend / total_kpi_cnt rounded to 4 decimals, returning NULL whenever total_kpi_cnt is 0.
    • If a goal in campaign_goal has zero post-launch activity, reporting it with 0 spend, 0 KPIs, and NULL cost follows "for each campaign_goal" literally (our test suite accepts either keeping or omitting completely idle goals; state your choice in an interview).
  2. Avoid the row-level join trap between spend and conversions

    The prompt mentions that spend and conversion rows can be joined on (date, advertiser_id, campaign_id, creative_group) when both are needed together. For Part 2, joining the two fact tables row by row is a classic SQL trap for two reasons:

    Trap 1 — Unmatched days disappear under an INNER JOIN:
      campaign_spend:      Jun 1 ($30), Jun 2 ($70)    --> true spend = $100
      campaign_conversion: Jun 1 (3 KPIs), Jun 3 (2)   --> true KPIs  = 5
      Row-level INNER JOIN matches ONLY Jun 1          --> wrong spend = $30, wrong KPIs = 3!
    
    Trap 2 — Duplicate keys multiply rows (fan-out):
      campaign_spend:      Jul 1, campaign 701, group 'A' -> ad_spend = $50
      campaign_conversion: two rows for Jul 1, 701, 'A'   -> kpi_cnt = 2 and kpi_cnt = 3
      Row-level JOIN repeats the $50 spend row twice      --> wrong spend = $100 instead of $50!
    

    Because total_ad_spend and total_kpi_cnt are independent sums, the clean architecture is aggregate first, join second: sum campaign_spend to one row per campaign_goal, sum campaign_conversion to one row per campaign_goal, and join those tiny 1-row-per-goal summaries at the end.

  3. Filter by each campaign's launch date and aggregate each fact table

    We build two Common Table Expressions (CTEs)—named temporary query blocks introduced with WITH—one for spend and one for conversions. In each CTE, joining to campaign_goal on campaign_id attaches both the campaign's campaign_goal and that specific campaign's campaign_launch_date:

    • WHERE s.date >= g.campaign_launch_date checks each row against its own campaign's launch date (>= includes launch day itself). In Example 1, app_install campaign 501 launches on 2025-04-11 while app_install campaign 601 launches on 2025-04-10, so filtering by one date per goal would be wrong.
    • An inner JOIN to campaign_goal naturally ignores orphan campaign_ids missing from campaign_goal, since they have no goal to group under.
    WITH spend_by_goal AS (
        -- Aggregate ad spend per goal on or after each campaign's own launch date
        SELECT
            g.campaign_goal,
            SUM(s.ad_spend) AS total_ad_spend
        FROM campaign_spend AS s
        JOIN campaign_goal AS g
            ON g.campaign_id = s.campaign_id
        WHERE s.date >= g.campaign_launch_date
        GROUP BY g.campaign_goal
    ),
    kpi_by_goal AS (
        -- Aggregate KPI conversions separately per goal so spend and conversion rows never multiply
        SELECT
            g.campaign_goal,
            SUM(c.kpi_cnt) AS total_kpi_cnt
        FROM campaign_conversion AS c
        JOIN campaign_goal AS g
            ON g.campaign_id = c.campaign_id
        WHERE c.date >= g.campaign_launch_date
        GROUP BY g.campaign_goal
    ),
    
  4. Combine spend and KPI totals safely with LEFT JOIN

    What if a goal has spend after launch but no conversion rows at all—or conversions after launch (say, delayed attributions) with $0 spend? Starting from one summary table alone would drop goals that only exist in the other!

    Instead, we collect every distinct campaign_goal from campaign_goal into a goals CTE and LEFT JOIN both spend_by_goal and kpi_by_goal onto it:

    • Each CTE has at most one row per campaign_goal, so joining them can never duplicate rows.
    • COALESCE(..., 0) turns a missing NULL sum into 0.
    goals AS (
        -- Start from every distinct goal so goals missing spend or conversions still appear
        SELECT DISTINCT campaign_goal
        FROM campaign_goal
    ),
    goal_totals AS (
        SELECT
            goals.campaign_goal,
            COALESCE(sp.total_ad_spend, 0) AS total_ad_spend,
            COALESCE(kp.total_kpi_cnt, 0) AS total_kpi_cnt
        FROM goals
        LEFT JOIN spend_by_goal AS sp
            ON sp.campaign_goal = goals.campaign_goal
        LEFT JOIN kpi_by_goal AS kp
            ON kp.campaign_goal = goals.campaign_goal
    )
    
  5. Compute cost_per_kpi without integer truncation or division by zero

    Finally, divide total_ad_spend by total_kpi_cnt for each goal:

    • 1.0 * total_ad_spend: Forces floating-point division. In SQLite, whole-dollar numbers like 250 and 9 are stored as integers, so 250 / 9 would otherwise truncate to 27 instead of 27.7778.
    • NULLIF(total_kpi_cnt, 0): Returns NULL when total_kpi_cnt equals 0. Dividing by NULL yields NULL cleanly in every SQL engine instead of raising a division-by-zero error in PostgreSQL, Snowflake, or SQL Server.
    • ROUND(..., 4): Rounds non-NULL ratios to four decimal places.
    -- Multiply by 1.0 for float division; NULLIF returns NULL instead of dividing by zero
    SELECT
        campaign_goal,
        total_ad_spend,
        total_kpi_cnt,
        ROUND(1.0 * total_ad_spend / NULLIF(total_kpi_cnt, 0), 4) AS cost_per_kpi
    FROM goal_totals
    
  6. Trace Example 1 step by step

    First, check which rows survive date >= campaign_launch_date for each campaign:

    campaign | goal        | launch     | post-launch spend       | post-launch kpi_cnt | pre-launch dropped
    ---------+-------------+------------+-------------------------+---------------------+--------------------------
    501      | app_install | 2025-04-11 | 90 + 30 = 120           | 11 + 4 = 15         | 04-10: spend 45, kpi 6
    502      | checkout    | 2025-04-10 | 150 + 100 = 250         | 5 + 4 = 9           | none
    601      | app_install | 2025-04-10 | 75 + 45 = 120           | 5 (no 04-11 row)    | none
    602      | lead        | 2025-04-12 | 85                      | 0                   | 04-11: spend 25, kpi 2
    

    Next, roll up by campaign_goal and compute cost_per_kpi:

    campaign_goal | total_ad_spend   | total_kpi_cnt | cost_per_kpi
    --------------+------------------+---------------+-------------------------------
    app_install   | 120 + 120 = 240  | 15 + 5 = 20   | ROUND(240.0 / 20, 4) = 12.0
    checkout      | 250              | 9             | ROUND(250.0 / 9,  4) = 27.7778
    lead          | 85               | 0             | NULL (NULLIF(0, 0) -> NULL)
    
  7. Complete SQL query

    Putting all CTEs and the final SELECT together gives the complete solution:

    WITH spend_by_goal AS (
        -- Aggregate ad spend per goal on or after each campaign's own launch date
        SELECT
            g.campaign_goal,
            SUM(s.ad_spend) AS total_ad_spend
        FROM campaign_spend AS s
        JOIN campaign_goal AS g
            ON g.campaign_id = s.campaign_id
        WHERE s.date >= g.campaign_launch_date
        GROUP BY g.campaign_goal
    ),
    kpi_by_goal AS (
        -- Aggregate KPI conversions separately per goal so spend and conversion rows never multiply
        SELECT
            g.campaign_goal,
            SUM(c.kpi_cnt) AS total_kpi_cnt
        FROM campaign_conversion AS c
        JOIN campaign_goal AS g
            ON g.campaign_id = c.campaign_id
        WHERE c.date >= g.campaign_launch_date
        GROUP BY g.campaign_goal
    ),
    goals AS (
        -- Start from every distinct goal so goals missing spend or conversions still appear
        SELECT DISTINCT campaign_goal
        FROM campaign_goal
    ),
    goal_totals AS (
        SELECT
            goals.campaign_goal,
            COALESCE(sp.total_ad_spend, 0) AS total_ad_spend,
            COALESCE(kp.total_kpi_cnt, 0) AS total_kpi_cnt
        FROM goals
        LEFT JOIN spend_by_goal AS sp
            ON sp.campaign_goal = goals.campaign_goal
        LEFT JOIN kpi_by_goal AS kp
            ON kp.campaign_goal = goals.campaign_goal
    )
    -- Multiply by 1.0 for float division; NULLIF returns NULL instead of dividing by zero
    SELECT
        campaign_goal,
        total_ad_spend,
        total_kpi_cnt,
        ROUND(1.0 * total_ad_spend / NULLIF(total_kpi_cnt, 0), 4) AS cost_per_kpi
    FROM goal_totals
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of campaign_spend as a box of daily ad-spend receipts, campaign_conversion as a separate box of daily conversion tally sheets, and campaign_goal as the master directory listing each campaign's goal (app_install, checkout, lead) and official launch date. To find the cost per KPI for each goal, you should not try to staple individual daily receipts to daily tally sheets first. Instead, sort all post-launch receipts into one pile per goal and add them up, separately sort all post-launch tally sheets into one pile per goal and add them up, and divide each goal's total spend by its total conversions at the very end.

Why does joining campaign_spend directly to campaign_conversion at the daily creative grain fail? First, an INNER JOIN silently drops spend on days when a creative got zero conversion rows (like Campaign 601 on 2025-04-11) and drops delayed conversions on days when spend was paused. Second, if two conversion rows exist for the same (date, advertiser_id, campaign_id, creative_group) key, joining before aggregating duplicates the matching spend row and double-counts the money (chasm trap). Aggregating each table independently to one row per campaign_goal before joining eliminates both bugs completely.

Here is how a mini-trace works on three campaigns—501 (app_install, launches Apr 11), 601 (app_install, launches Apr 10), and 602 (lead, launches Apr 12):

1. Filter each fact table against its own campaign's launch_date and sum by goal:
   - spend_by_goal:
       501 drops Apr 10 ($45), keeps Apr 11 ($90 + $30 = $120)
       601 keeps Apr 10–11 ($75 + $45 = $120)                 --> app_install spend = 240
       602 drops Apr 11 ($25), keeps Apr 12 ($85)             --> lead        spend = 85
   - kpi_by_goal:
       501 drops Apr 10 (6), keeps Apr 11 (11 + 4 = 15)
       601 keeps Apr 10 (5; no Apr 11 row)                    --> app_install KPIs = 20
       602 drops Apr 11 (2), keeps Apr 12 (0)                 --> lead        KPIs = 0

2. Join 1-row-per-goal summaries onto distinct goals and divide safely:
   - app_install: 1.0 * 240 / 20 = 12.0
   - lead:        1.0 * 85 / NULLIF(0, 0) = NULL

Key SQL terms used in this solution:

  • Grain: The exact combination of columns that uniquely defines what a single row represents (for example, one row per (date, campaign_id, creative_group) vs one row per campaign_goal).
  • Chasm trap (fan-out): A join bug where joining two multi-row fact tables through shared keys multiplies rows and inflates SUM aggregates.
  • CTE (Common Table Expression): A named step (WITH name AS (...)) that lets us aggregate each fact table cleanly before combining results.
  • LEFT JOIN + COALESCE(x, 0): Keeps every goal from goals even when one side has no matching rows, turning missing NULL sums into 0.
  • NULLIF(x, 0): Returns NULL if x equals 0 (and x otherwise), preventing division-by-zero errors when total_kpi_cnt is 0.

Complexity

Let S, C, and G be the number of rows in campaign_spend, campaign_conversion, and campaign_goal, and let K be the number of distinct campaign_goal values (K <= G, typically tiny, such as 3–10 KPI types).

  • Time: O(S + C + G) average time using hash joins and hash aggregation (or O((S + C) log G) if the engine uses sort/index joins). spend_by_goal builds an O(G) lookup table from campaign_goal, scans all S spend rows once, checks s.date >= g.campaign_launch_date, and accumulates sums into K goal buckets. kpi_by_goal does the exact same single pass over the C conversion rows. The final LEFT JOINs combine three tiny tables of at most K rows each in O(K) time.
  • Space: O(G + K) memory—O(G) to hold the campaign_id -> (campaign_goal, campaign_launch_date) hash map during the joins and O(K) for the per-goal running totals. Unlike a row-level join between campaign_spend and campaign_conversion, it never materializes a large intermediate fact table.

Indexes: A primary-key index on campaign_goal(campaign_id) speeds up campaign lookups, and composite indexes on campaign_spend(campaign_id, date) and campaign_conversion(campaign_id, date) allow the engine to jump straight to date >= campaign_launch_date for each campaign instead of scanning pre-launch history. In cloud data warehouses partitioned by date, adding a static lower bound like WHERE s.date >= '2025-01-01' (the minimum launch date of interest) enables partition pruning.

Edge cases

  • Exact launch date vs pre-launch rows: date >= campaign_launch_date includes activity on launch day itself and excludes pre-launch test rows on both spend and conversions.
  • Different launch dates within the same goal: Each row joins on campaign_id, so Campaign 501 (2025-04-11) and Campaign 601 (2025-04-10) each enforce their own launch date before pooling into 'app_install'.
  • Zero KPI conversions (total_kpi_cnt = 0): NULLIF(total_kpi_cnt, 0) evaluates to NULL, producing cost_per_kpi = NULL without crashing.
  • Spend days without conversion rows (or conversion days without spend rows): Both are counted accurately because the two fact tables are never joined row by row.
  • Multiple rows per (date, advertiser_id, campaign_id, creative_group) key: Pre-aggregating each fact table separately prevents row multiplication.
  • Goal with conversions after launch but $0 spend: Kept via the goals spine with total_ad_spend = 0 and cost_per_kpi = 0.0 (starting from spend_by_goal alone would lose this goal!).
  • Campaigns missing from campaign_goal: Excluded by the inner JOIN to campaign_goal because they have no assigned goal or launch date.
  • Empty tables: If campaign_goal is empty, goals is empty and the query cleanly returns zero rows.

Common mistakes

  • Joining campaign_spend to campaign_conversion before aggregating: Drops unmatched days on an INNER JOIN and double-counts spend whenever conversion rows repeat a key.
  • Summing installs instead of kpi_cnt: In Example 1, Campaign 502 (checkout) has 12 installs and 5 checkout KPIs on Apr 10, and Campaign 602 (lead) has 9 installs and 0 lead KPIs on Apr 12—summing installs measures the wrong event!
  • Using one launch date per goal (MIN(campaign_launch_date)): Lets pre-launch test spend and conversions from later campaigns (like Campaign 501 on Apr 10) leak into the goal's totals.
  • Filtering spend by launch date while forgetting to filter conversions (or vice versa): Mixes post-launch spend with all-time conversions, distorting the ratio.
  • Averaging per-campaign CPAs (AVG(campaign_spend / campaign_kpi)): The overall cost per KPI for a goal is a ratio of sums (SUM(spend) / SUM(kpi)), not an unweighted average of campaign ratios, which overweights tiny campaigns.
  • Integer division (total_ad_spend / total_kpi_cnt without 1.0 *): Truncates 250 / 9 to 27 instead of 27.7778 when spend is stored as whole numbers in SQLite.

Follow-up questions

  • How would you write the SQL query for Part 1 to return each day's top 3 spending advertisers while keeping ties? Roll up ad_spend at the (date, advertiser_id) grain first, then evaluate a window function—a calculation over a partitioned slice of rows that keeps individual rows intact—with RANK() OVER (PARTITION BY date ORDER BY daily_ad_spend DESC). Filtering WHERE spend_rank <= 3 retains every advertiser tied within ranks 1 through 3 on each date (note that Part 1 sums all daily spend without filtering by campaign_launch_date):

sql WITH daily_spend AS ( SELECT date, advertiser_id, SUM(ad_spend) AS daily_ad_spend FROM campaign_spend GROUP BY date, advertiser_id ), ranked_daily AS ( SELECT date, advertiser_id, daily_ad_spend, 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_daily WHERE spend_rank <= 3 ORDER BY date, spend_rank, advertiser_id

  • When daily ad spends tie in Part 1, how do RANK(), DENSE_RANK(), and ROW_NUMBER() behave differently? Suppose five advertisers on one day spend 100, 100, 80, 80, 50. ROW_NUMBER() hands out 1, 2, 3, 4, 5 and arbitrarily drops one of the $80 advertisers—breaking the tie-preservation requirement. RANK() assigns standard competition ranks 1, 1, 3, 3, 5 (skipping 2 because two advertisers beat $80) and returns 4 advertisers, whereas DENSE_RANK() assigns 1, 1, 2, 2, 3 (the top 3 distinct spend levels) and returns all 5; RANK() is the standard SQL convention for "top 3 ranks," and stating the distinction clearly earns strong marks.

  • Why is it misleading to compare raw cost_per_kpi across different goals like app_install and checkout, and how does conversion lag affect recent days? Different goals measure completely different funnel depths and unit economics: driving a completed 'checkout' ($27.78 in Example 1) naturally costs more than driving a free 'app_install' ($12.00), yet a checkout may yield far higher profit margin—so compare cost_per_kpi within the same goal or against goal-specific target CPAs / ROAS. Furthermore, ad spend is logged immediately upon impression delivery while downstream conversions (especially checkouts) often arrive days later; including recent unmatured dates spikes cost_per_kpi upward unless you either exclude the trailing attribution window (e.g., date <= CURRENT_DATE - 7) or evaluate fixed click-cohort windows (such as 7-day click-through CPA).

Follow-up questions

Similar questions

More Moloco interview questions

All 5 Moloco questions →