Rank Advertisers by User Complaint Rate Over a 7-Day Window
SQL & DataModel answerLast updated
Write SQL that finds the worst advertisers by report-to-visit rate, picks each one's worst ad, and builds a daily leaderboard without double-counting visits or reports.
You work on an ad-safety team. Users open ad landing pages (visits) and sometimes flag an ad (reports). Use ANSI SQL. Treat today as 2025-09-01, and define "the last 7 days" as 2025-08-26 00:00:00 through 2025-09-01 23:59:59 UTC.
Schema
advertisers(advertiser_id INT, name TEXT)ads(ad_id INT, advertiser_id INT, created_at TIMESTAMP)ad_page_visits(visit_id BIGINT, ad_id INT, user_id BIGINT, visited_at TIMESTAMP)ad_reports(report_id BIGINT, ad_id INT, user_id BIGINT, reported_at TIMESTAMP, reason TEXT)
Sample rows
ads
| ad_id | advertiser_id | created_at |
|---|---|---|
| 1 | 101 | 2025-08-15 10:00:00 |
| 2 | 101 | 2025-08-20 11:00:00 |
| 3 | 102 | 2025-08-25 12:00:00 |
| 4 | 103 | 2025-08-28 09:00:00 |
ad_page_visits (10 rows): ad 1 has visits 1-3 (users 1001, 1002, 1003, on 08-26 and 08-27). Ad 2 has visits 4-5 (users 1001, 1004). Ad 3 has visits 6-7 (users 1002, 1005). Ad 4 has visits 8-10 (users 1006, 1002, 1007, from 08-31 to 09-01).
ad_reports (5 rows): report 500 (ad 1, user 1002), 501 (ad 1, user 1003), 502 (ad 2, user 1004), 503 (ad 3, user 1005), 504 (ad 4, user 1006). Each is filed a few minutes after the matching visit.
advertisers holds 101 Alpha Co, 102 Beta LLC and 103 Gamma Inc.
Tasks
A. Worst advertisers. An advertiser qualifies if, in the window, it has at least 1,000 page visits and at least 50 distinct reporting users. Rank qualifiers by report_rate = total_reports / total_visits descending. Write one query returning advertiser_id, total_visits, total_reports, unique_reporters, report_rate, rank, keeping only ranks 1 to 5. Use a window function (RANK or DENSE_RANK). Break ties by total_reports descending, then advertiser_id ascending.
B. Worst ad. Extend the query so that, for advertisers with more than one ad, it also returns the ad_id with the highest ad-level report rate in the window. Only ads with at least 100 visits are eligible. Break ties by ad-level report count descending, then ad_id ascending.
C. Daily leaderboard. Return one row per advertiser per day in the window, with that day's rank by report rate. Only include advertisers with at least 200 visits that day. Advertisers with zero reports that day must still appear with rate 0, and days with no visits must not appear.
D. Explain in SQL comments (1) how your query avoids double-counting when a user visits and reports within the same minute, and (2) how it treats reports that have no matching visit row in the window.
The sample data is too small to meet the thresholds, so reason about the logic rather than expecting rows back.
Hints
Hint 1
Never join visits directly to reports. Aggregate each table to its own grain (per ad, per advertiser, or per advertiser-day) and join only the aggregates on a key that is unique on both sides.
Hint 2
Use a half-open window (`>= '2025-08-26'` and `< '2025-09-02'`) instead of `BETWEEN ... '23:59:59'`, and compute advertiser-level distinct reporters with `COUNT(DISTINCT user_id)` over all of the advertiser's ads, not by summing per-ad distinct counts.
Hint 3
Apply the visit and reporter thresholds before the `RANK()` so the rank is among qualifiers. For B use `ROW_NUMBER() OVER (PARTITION BY advertiser_id ...)`, and for C use `RANK() OVER (PARTITION BY day ...)` with a LEFT JOIN from daily visits to daily reports.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Visits and reports are two independent fact tables. Joining them row to row would multiply rows (a user with 3 visits and 2 reports yields 6 rows) and inflate every count. The safe pattern is:
- Aggregate visits and reports separately to the grain you need.
- Join the aggregates on a key that is unique on both sides, so the join is 1:1 and cannot fan out.
- Filter first, then rank, so "top 5" means the top 5 qualifiers.
Other decisions:
- Window: use
ts >= '2025-08-26 00:00:00' AND ts < '2025-09-02 00:00:00'.BETWEEN ... '23:59:59'silently drops events with fractional seconds on the last day. - Unique reporters: compute
COUNT(DISTINCT user_id)at advertiser grain. Summing per-ad distinct counts double-counts a user who reported two ads from the same advertiser. - Rate: cast to
DOUBLE PRECISIONbefore dividing to avoid integer division. Equal fractions such as 1/3 and 2/6 give identical doubles, so real ties stay ties. The visit thresholds guarantee a non-zero denominator. - Zero reports: drive from the visits side and
LEFT JOINreports withCOALESCE(..., 0).
Parts A, B and D
-- Window: [2025-08-26 00:00:00, 2025-09-02 00:00:00) UTC.
--
-- D1) No double counting: visits and reports are aggregated in separate CTEs
-- and only the aggregates are joined, on ad_id / advertiser_id (unique on
-- both sides). Visit rows are never matched to report rows by user or time,
-- so a user who visits and reports in the same minute adds exactly 1 visit
-- and 1 report. COUNT(DISTINCT visit_id / report_id) also protects against
-- an event being ingested twice.
-- D2) Reports with no visit: reports are counted from ad_reports alone, by
-- reported_at. They count even if the matching visit is outside the window
-- or missing. Visits are the independent denominator. Reports whose ad_id
-- is not in ads are dropped by the inner join to ads (orphans: monitor them).
WITH ad_visits AS (
SELECT ad_id, COUNT(DISTINCT visit_id) AS visits
FROM ad_page_visits
WHERE visited_at >= TIMESTAMP '2025-08-26 00:00:00'
AND visited_at < TIMESTAMP '2025-09-02 00:00:00'
GROUP BY ad_id
),
ad_reps AS (
SELECT ad_id, COUNT(DISTINCT report_id) AS reports
FROM ad_reports
WHERE reported_at >= TIMESTAMP '2025-08-26 00:00:00'
AND reported_at < TIMESTAMP '2025-09-02 00:00:00'
GROUP BY ad_id
),
adv_visits AS (
SELECT a.advertiser_id, SUM(av.visits) AS total_visits
FROM ad_visits av
JOIN ads a ON a.ad_id = av.ad_id
GROUP BY a.advertiser_id
),
adv_reps AS ( -- distinct reporters need advertiser grain
SELECT a.advertiser_id,
COUNT(DISTINCT r.report_id) AS total_reports,
COUNT(DISTINCT r.user_id) AS unique_reporters
FROM ad_reports r
JOIN ads a ON a.ad_id = r.ad_id
WHERE r.reported_at >= TIMESTAMP '2025-08-26 00:00:00'
AND r.reported_at < TIMESTAMP '2025-09-02 00:00:00'
GROUP BY a.advertiser_id
),
adv_stats AS ( -- 1:1 join of aggregates
SELECT v.advertiser_id,
v.total_visits,
COALESCE(r.total_reports, 0) AS total_reports,
COALESCE(r.unique_reporters, 0) AS unique_reporters,
CAST(COALESCE(r.total_reports, 0) AS DOUBLE PRECISION)
/ v.total_visits AS report_rate
FROM adv_visits v
LEFT JOIN adv_reps r ON r.advertiser_id = v.advertiser_id
),
ranked AS ( -- A: filter, then rank
SELECT s.*,
RANK() OVER (ORDER BY s.report_rate DESC,
s.total_reports DESC,
s.advertiser_id ASC) AS rnk
FROM adv_stats s
WHERE s.total_visits >= 1000
AND s.unique_reporters >= 50
),
ad_stats AS ( -- B: ad-level rate, eligible ads only
SELECT a.advertiser_id, v.ad_id,
COALESCE(r.reports, 0) AS reports,
CAST(COALESCE(r.reports, 0) AS DOUBLE PRECISION) / v.visits AS ad_rate
FROM ad_visits v
JOIN ads a ON a.ad_id = v.ad_id
LEFT JOIN ad_reps r ON r.ad_id = v.ad_id
WHERE v.visits >= 100
),
worst_ad AS (
SELECT advertiser_id, ad_id,
ROW_NUMBER() OVER (PARTITION BY advertiser_id
ORDER BY ad_rate DESC, reports DESC, ad_id ASC) AS rn
FROM ad_stats
),
ad_counts AS (
SELECT advertiser_id, COUNT(*) AS n_ads FROM ads GROUP BY advertiser_id
)
SELECT k.advertiser_id, k.total_visits, k.total_reports, k.unique_reporters,
k.report_rate, k.rnk AS "rank",
CASE WHEN c.n_ads > 1 THEN w.ad_id END AS worst_ad_id
FROM ranked k
JOIN ad_counts c ON c.advertiser_id = k.advertiser_id
LEFT JOIN worst_ad w ON w.advertiser_id = k.advertiser_id AND w.rn = 1
WHERE k.rnk <= 5
ORDER BY k.rnk;
Notes:
RANK()with all three sort keys is effectively unique, so the top 5 is deterministic. If you used onlyreport_rate, ties could return more than 5 rows.ROW_NUMBER()is right for the worst ad because exactly one ad per advertiser is wanted.worst_ad_idisNULLfor single-ad advertisers, or when no ad reaches 100 visits.
Part C: daily leaderboard
WITH day_visits AS (
SELECT a.advertiser_id,
CAST(v.visited_at AS DATE) AS day,
COUNT(DISTINCT v.visit_id) AS visits
FROM ad_page_visits v
JOIN ads a ON a.ad_id = v.ad_id
WHERE v.visited_at >= TIMESTAMP '2025-08-26 00:00:00'
AND v.visited_at < TIMESTAMP '2025-09-02 00:00:00'
GROUP BY a.advertiser_id, CAST(v.visited_at AS DATE)
HAVING COUNT(DISTINCT v.visit_id) >= 200
),
day_reports AS (
SELECT a.advertiser_id,
CAST(r.reported_at AS DATE) AS day,
COUNT(DISTINCT r.report_id) AS reports
FROM ad_reports r
JOIN ads a ON a.ad_id = r.ad_id
WHERE r.reported_at >= TIMESTAMP '2025-08-26 00:00:00'
AND r.reported_at < TIMESTAMP '2025-09-02 00:00:00'
GROUP BY a.advertiser_id, CAST(r.reported_at AS DATE)
),
scored AS (
SELECT dv.day, dv.advertiser_id, dv.visits,
COALESCE(dr.reports, 0) AS reports,
CAST(COALESCE(dr.reports, 0) AS DOUBLE PRECISION) / dv.visits AS report_rate
FROM day_visits dv
LEFT JOIN day_reports dr
ON dr.advertiser_id = dv.advertiser_id AND dr.day = dv.day
)
SELECT day, advertiser_id, visits, reports, report_rate,
RANK() OVER (PARTITION BY day
ORDER BY report_rate DESC, reports DESC, advertiser_id ASC) AS "rank"
FROM scored
ORDER BY day, "rank";
Because the base is day_visits, days with no visits never appear. Advertisers below 200 visits that day are removed by HAVING before ranking. A LEFT JOIN plus COALESCE keeps zero-report advertisers with rate 0.
Complexity
Each CTE is a single scan with a hash or sort aggregate, so about O(V + R + A) plus the sorts for the window functions. Indexes on (visited_at, ad_id) and (reported_at, ad_id) let the engine prune to the 7-day range.
Common mistakes
- Joining visits to reports directly, which inflates visit and report counts.
- Using
BETWEENwith23:59:59and losing fractional-second events. - Summing per-ad distinct reporters instead of counting distinct users at advertiser level.
- Integer division, which turns every rate below 1 into 0.
- Ranking before applying the thresholds, so unqualified advertisers consume ranks.
- Starting Part C from reports, which creates rows for days with no visits and breaks the "zero reports still appear" rule.
- Using
RANKfor the worst ad, which can return two ads on a full tie.