Skip to content

Two cheapest campaigns per month by cost per click

The task

The marketing team wants to see which campaigns bought clicks most cheaply each month. For each campaign and calendar month (month of day in ad_daily), the cost per click is the total spend divided by the total clicks for that month. A campaign is only compared in a month when it had at least 1000 clicks in total that month.

Rank the eligible campaigns inside each month by cost per click, lowest first, using the exact value. Campaigns with the same cost per click share a rank, and the next rank skips ahead (1, 1, 3). Keep every campaign with rank 2 or better, so ties at the cut-off are all kept.

Return month (the first day of the month), campaign_name, cost_per_click (rounded to 3 decimal places) and cpc_rank. Sort by month ascending, then cpc_rank ascending, then campaign_name ascending.

Expected output

monthcampaign_namecost_per_clickcpc_rank
  • Sorted by month ascending, then cpc_rank ascending, then campaign_name ascending.
  • Numbers rounded to 3 decimal places.
  • Checked on the sample and on 2 hidden datasets. How grading works

Tables Marketing team · click a name to insert it

campaigns10 rows in the sample

One row per campaign. Key: campaign_id.

intUnique id.
textName.
textsearch, social, video, email or affiliate.
dateFirst day live.
dateLast day live. NULL if still running.
numeric(10,2)Budget per day, USD.
ad_daily969 rows in the sample

One row per campaign per day it served ads. Days with no delivery have no row. Key: campaign_id, day.

intThe campaign.
dateThe day.
intTimes an ad was shown.
intClicks.
numeric(10,2)Money spent, USD.
signups2,108 rows in the sample

One row per new user. campaign_id is the campaign credited with the sign-up. Key: user_id.

intUnique id.
timestampWhen they signed up (UTC).
intCredited campaign. NULL for organic sign-ups.
textTwo-letter country code.
purchases2,294 rows in the sample

One row per paid order by a user. Key: purchase_id.

intUnique id.
intBuyer.
timestampWhen (UTC).
numeric(10,2)Order value, USD.

Related questions

Loading the editor and PostgreSQL