Top Three Advertisers by Spend Share in Each Country
Last updated: November 29, 2026
Quick Overview
Given daily ad spend by advertiser and country, write SQL that returns the top three advertisers per country over the last 30 days with each one's share of country spend and the cumulative share.
Meta
November 29, 20260
0
0 solved
Given daily ad spend by advertiser and country, write SQL that returns the top three advertisers per country over the last 30 days with each one's share of country spend and the cumulative share.
Concentration of ad spend by market is a routine Ads finance and sales analytics question at Meta. The interviewer checks partitioned aggregates, deterministic ranking with ties, cumulative windows, and correct date filtering.
What the Interviewer Expects
- Aggregates spend per advertiser and country before ranking
- Computes share with a partitioned SUM window
- Chooses and justifies a ranking function for ties
- Computes cumulative share in rank order
- Uses a half-open date range for the last 30 days
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you handle spend recorded in different currencies?
- Should ties at rank 3 both be included? How would the query change?
- How would you add the change in each advertiser's share versus the prior 30 days?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Table: ad_spend(advertiser_id, country, spend_date, spend_usd). Spend is already in USD (if not, join to a daily FX table). "Last 30 days" means the 30 complete days before today. Ties at rank 3: I ...
Approach
- Filter to the date range and sum spend per (country, advertiser).
- In the same step, compute country total with
SUM() OVER (PARTITION BY country)and rank withROW_NUMBER(). - Keep ranks 1 t...