Top Campaign by User Revenue

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L5
Asked in
Airbnb

Problem

For each user who clicked an ad, find which campaign generated the most revenue for that user. If multiple campaigns tie for the top, list each qualifying entry only once. Show the user and the top campaign.

Which campaign made each user spend the most?

Tables

ad_impressions

Columns: impression_id INTEGER, user_id INTEGER, ad_campaign TEXT, impression_time TEXT, clicked INTEGER, revenue REAL

ad_impressions: 10 of 200 rows
impression_iduser_idad_campaignimpression_timeclickedrevenue
253100BRAND_AWARENESS_Q12026-02-02 01:07:000NULL
306197PRODUCT_LAUNCH_X2026-03-03 02:14:000NULL
359294RETARGETING_CART2026-04-04 03:21:000NULL
412391HOLIDAY_PROMO2026-05-05 04:28:000NULL
465488NEW_USER_ACQU2026-06-06 05:35:0010.2
518NULLLOYALTY_PROGRAM2026-07-07 06:42:000NULL
571682FLASH_SALE_48H2026-08-08 07:49:000NULL
624779SUMMER_SALE_20242026-09-09 08:56:000NULL
677876BRAND_AWARENESS_Q12026-01-10 09:03:000NULL
730973PRODUCT_LAUNCH_X2026-02-11 10:10:0010.35

Expected output

First 5 of 17 rows
user_idad_campaign
NULLPRODUCT_LAUNCH_X
488FLASH_SALE_48H
973HOLIDAY_PROMO
2137LOYALTY_PROGRAM
3301SUMMER_SALE_2024

Worked solution and explanation

Why this problem exists in real interviews

Per-group top-N is a daily request from analytics. The candidate must recognize that ranking happens within each user (partitioned), not across the whole table, and that ties produce multiple rows the interviewer expects to see deduplicated cleanly.


Break down the requirements


The solution

WITH ranked AS (
  SELECT user_id, ad_campaign,
         DENSE_RANK() OVER (PARTITION BY user_id ORDER BY revenue DESC) AS rnk
  FROM ad_impressions
  WHERE clicked = 1
)
SELECT DISTINCT r.user_id, r.ad_campaign
FROM ranked r
WHERE r.rnk = 1

Common follow-up questions