Rolling Window Metrics for Digital Ad Campaign Data
SQL & DataModel answerLast updated
Compute impression rankings, conversion rates by format, per-user revenue, and peak traffic hours from ad event tables using SQL aggregation and joins.
You have two tables tracking digital advertising events:
Table: ad_impressions
impression_id(integer, primary key)ad_id(integer)campaign_id(integer)ad_type(string: 'video', 'display', or 'search')impression_time(timestamp)user_id(integer)
Table: ad_conversions
conversion_id(integer, primary key)impression_id(integer, foreign key toad_impressions)conversion_value(decimal)conversion_time(timestamp)
Write SQL queries to answer each question below. Use 2023-10-31 23:59:59 as the reference point for "now."
Questions
1. Which three ads generated the most impressions during the most recent 30-day period? Return ad_id and impression count, handling ties appropriately.
2. What is the conversion rate for each ad format over the last 30 days? Define conversion rate as the number of conversions divided by the number of impressions.
3. For each campaign, what is the mean conversion value per distinct user who was exposed to that campaign? Include all campaigns and all time periods.
4. Which hour of the day (0-23, UTC) receives the highest volume of impressions? Consider the entire history and return all hours that tie for the maximum.
Notes
- The 30-day window is exclusive on the left, inclusive on the right:
(reference_time - 30 days, reference_time] - One impression may generate multiple conversions
- Not all impressions result in conversions
- For question 3, "per user" means divide total conversion revenue by the count of unique users, not unique converters
Hints
Hint 1
Use LEFT JOIN to preserve impressions that never converted when computing rates
Hint 2
COUNT(DISTINCT ...) prevents double-counting when a join creates duplicate rows
Hint 3
Cast to numeric or float before division to avoid integer truncation
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each task requires filtering, joining, and aggregating events across two tables. The core challenges are:
- Time window logic: Pin calculations to the given timestamp rather than database system time
- Join direction: Impressions form the base population; use LEFT JOIN to retain non-converting impressions
- Avoiding double-counts: When one impression links to multiple conversions, use DISTINCT counts where appropriate
- Division safety: Cast integers to decimal before dividing to prevent truncation
I'll clarify ambiguities before writing queries:
- "Last 30 days" means impressions between 2023-10-01 23:59:59 (exclusive) and 2023-10-31 23:59:59 (inclusive)
- Questions 3 and 4 don't specify a time window, so I'll treat them as all-time analyses
- "Conversion rate" here means conversions per impression (not clicks per impression, which is the traditional CTR definition)
Solutions
Query 1: Top Three Ads by Recent Impression Volume
WITH recent_impressions AS (
SELECT ad_id, COUNT(*) AS impression_count
FROM ad_impressions
WHERE impression_time > TIMESTAMP '2023-10-31 23:59:59' - INTERVAL '30 days'
AND impression_time <= TIMESTAMP '2023-10-31 23:59:59'
GROUP BY ad_id
),
ranked_ads AS (
SELECT ad_id,
impression_count,
DENSE_RANK() OVER (ORDER BY impression_count DESC) AS rank_position
FROM recent_impressions
)
SELECT ad_id, impression_count
FROM ranked_ads
WHERE rank_position <= 3
ORDER BY impression_count DESC, ad_id;
Key decisions:
DENSE_RANK()includes all ads tied at the third-highest count (e.g., if four ads tie for third place, all four appear)- If exactly three rows are required, add a tiebreaker:
ORDER BY impression_count DESC, ad_id LIMIT 3
Query 2: Conversion Rate by Ad Format
SELECT
i.ad_type,
COUNT(DISTINCT i.impression_id) AS total_impressions,
COUNT(c.conversion_id) AS total_conversions,
COUNT(c.conversion_id)::NUMERIC /
NULLIF(COUNT(DISTINCT i.impression_id), 0) AS conversion_rate
FROM ad_impressions i
LEFT JOIN ad_conversions c ON i.impression_id = c.impression_id
WHERE i.impression_time > TIMESTAMP '2023-10-31 23:59:59' - INTERVAL '30 days'
AND i.impression_time <= TIMESTAMP '2023-10-31 23:59:59'
GROUP BY i.ad_type
ORDER BY i.ad_type;
Why this works:
- LEFT JOIN ensures impressions without conversions still contribute to the denominator
COUNT(c.conversion_id)ignores NULLs from unmatched rows, counting only actual conversionsCOUNT(DISTINCT i.impression_id)in the denominator handles cases where one impression generates multiple conversions (which would duplicate impression rows in the join result)- Casting to NUMERIC prevents integer division (5/100 would otherwise return 0)
NULLIFguards against division by zero
Query 3: Mean Revenue Per Exposed User by Campaign
SELECT
i.campaign_id,
COUNT(DISTINCT i.user_id) AS unique_users_exposed,
COALESCE(SUM(c.conversion_value), 0) AS total_revenue,
COALESCE(SUM(c.conversion_value), 0) /
NULLIF(COUNT(DISTINCT i.user_id), 0) AS avg_revenue_per_user
FROM ad_impressions i
LEFT JOIN ad_conversions c ON i.impression_id = c.impression_id
GROUP BY i.campaign_id
ORDER BY i.campaign_id;
Interpretation:
- Denominator counts every distinct user who saw the campaign, regardless of conversion status
- A user who converts multiple times contributes all their revenue to the numerator but counts once in the denominator
COALESCEreturns 0 instead of NULL for campaigns with no conversions
Query 4: Peak Traffic Hour
WITH hourly_volume AS (
SELECT
EXTRACT(HOUR FROM impression_time)::INTEGER AS hour_utc,
COUNT(*) AS impression_count,
RANK() OVER (ORDER BY COUNT(*) DESC) AS volume_rank
FROM ad_impressions
GROUP BY EXTRACT(HOUR FROM impression_time)
)
SELECT hour_utc, impression_count
FROM hourly_volume
WHERE volume_rank = 1
ORDER BY hour_utc;
Details:
EXTRACT(HOUR ...)collapses timestamps across all dates into 24 buckets (0-23)RANK() = 1returns every hour tied for maximum volume- Result is in UTC as specified
Complexity
With I impressions and C conversions:
- Time: O(I + C) for each query (scan + hash join + hash aggregation).
COUNT(DISTINCT)adds O(I log I) within each group for sorting unique values. - Space: O(G) where G is the number of groups, plus O(C) for the join hash table.
Index recommendations:
ad_impressions(impression_time)accelerates the 30-day range filterad_conversions(impression_id)speeds up the join lookup
Common Mistakes
- Integer division:
5/100returns 0 in SQL. Cast at least one operand to NUMERIC or FLOAT. - Wrong join direction: Starting from conversions excludes impressions that never converted, understating the denominator.
- Filter placement: Putting time filters on the conversion table accidentally converts LEFT JOIN to INNER JOIN. Always filter the impression table in the WHERE clause.
- Forgetting DISTINCT: When joins duplicate rows, use
COUNT(DISTINCT ...)for the denominator. - NULL handling: Use
COALESCEorNULLIFto handle campaigns with zero conversions or empty groups. - Arbitrary tie-breaking: A simple
LIMIT 3without ordering by a unique column produces nondeterministic results when values tie.
Edge Cases
- Ad formats with zero impressions in the window won't appear unless you outer-join from a dimension table
- Conversions referencing impressions outside the 30-day window are correctly excluded (the filter happens before the join)
- NULL
user_idvalues (anonymous traffic) are ignored byCOUNT(DISTINCT)— confirm whether this matches business requirements - Boundary behavior: the window includes impressions at exactly
2023-10-31 23:59:59