KatInterview

Daily Revenue from Impression-Active Ads, Split by Origin

SQL & DataModel answer
EasyModel answerSQL & Datasqljoinsaggregation

Last updated

Write a SQL query that reports, per UTC day and ad origin, how many ads were active and how much revenue those ads earned on days they were active.

Daily revenue from active ads, grouped by how the ad was created

An advertising platform stores ad metadata, impression logs and revenue events. You need a daily report that shows how much money was earned by active ads, split by the way each ad was originally created.

Schema

ads

columntypenotes
ad_idBIGINTprimary key
advertiser_idBIGINT
creation_sourceVARCHARfor example 'SELF_SERVE', 'MANAGED', 'API'
created_atTIMESTAMP

ad_impressions

columntypenotes
impression_idBIGINTprimary key
ad_idBIGINTforeign key to ads.ad_id
impression_timeTIMESTAMP

ad_revenue_events

columntypenotes
event_idBIGINTprimary key
ad_idBIGINTforeign key to ads.ad_id
event_timeTIMESTAMPwhen the revenue was earned (for example per impression or click)
revenue_usdDECIMAL(18,6)

Definitions

  • All timestamps are in UTC, and a "day" is a UTC calendar date.
  • An ad is active on a given day if it has at least one impression on that day.
  • Active ad revenue for a day is the sum of revenue_usd from revenue events on that day, counting only events that belong to ads that are active on that same day.

Task

For every calendar day between :start_date and :end_date (both inclusive), return one row per creation_source with:

  • report_date
  • creation_source
  • active_ads: the number of distinct active ads
  • active_ad_revenue_usd: total revenue from those active ads

Sort by report_date, then creation_source.

What to cover in your answer

  • The query itself.
  • Why your join does not inflate revenue.
  • How you treat an ad that is active but earned nothing that day.
  • How you handle the inclusive end date when columns are timestamps.
  • Any other edge cases you would raise (missing creation_source, revenue on days with no impressions, empty days or sources).

Hints

Hint 1

Think about the grain of each table. Impressions are many per ad per day, and so are revenue events. What happens to revenue if you join the two raw tables on ad_id and date?

Hint 2

Reduce both fact tables to one row per (ad_id, day) before joining: a DISTINCT list of active ad-days, and a SUM of revenue per ad-day.

Hint 3

Make the active ad-days the driving table and LEFT JOIN the daily revenue onto it, so active ads with zero revenue are still counted. Filter the date range with a half-open predicate (< end_date + 1 day) rather than BETWEEN on timestamps.