Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Median CTR by Meta Campaign

HardSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Median CTR by Meta Campaign. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Meta Ads analysts want to compare campaign performance using the median click-through rate (CTR) across daily delivery records. Write a PostgreSQL query to return the median CTR for each ad campaign using window functions.

CTR for a row is defined as clicks::numeric / impressions. Rows with impressions = 0 or impressions IS NULL should be excluded from the median calculation.

Requirements

  1. Compute CTR for each valid row in ad_delivery.
  2. For each campaign_id, calculate the median CTR using window functions rather than PERCENTILE_CONT.
  3. If a campaign has an odd number of valid CTR rows, return the middle CTR.
  4. If a campaign has an even number of valid CTR rows, return the average of the two middle CTR values.
  5. Output campaign_id, campaign_name, and median_ctr, ordered by campaign_id.

Schema

meta_campaigns
ColumnTypeDescription
campaign_idPKINTUnique campaign identifier
campaign_nameVARCHAR(100)Campaign name in Meta Ads Manager
objectiveVARCHAR(50)Campaign objective
ad_delivery
ColumnTypeDescription
delivery_idPKINTUnique delivery record
campaign_idINTCampaign identifier
delivery_dateDATEDaily delivery date
impressionsINTNumber of impressions served
clicksINTNumber of clicks received
Tablesmeta_campaignsad_delivery
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results