KatInterview

Rolling Window Metrics for Digital Ad Campaign Data

SQL & DataModel answer
MediumModel answerSQL & Datasqlaggregationjoins

Last 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 to ad_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