Daily Revenue from Impression-Active Ads, Split by Origin
SQL & DataModel answerLast 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
| column | type | notes |
|---|---|---|
ad_id | BIGINT | primary key |
advertiser_id | BIGINT | |
creation_source | VARCHAR | for example 'SELF_SERVE', 'MANAGED', 'API' |
created_at | TIMESTAMP |
ad_impressions
| column | type | notes |
|---|---|---|
impression_id | BIGINT | primary key |
ad_id | BIGINT | foreign key to ads.ad_id |
impression_time | TIMESTAMP |
ad_revenue_events
| column | type | notes |
|---|---|---|
event_id | BIGINT | primary key |
ad_id | BIGINT | foreign key to ads.ad_id |
event_time | TIMESTAMP | when the revenue was earned (for example per impression or click) |
revenue_usd | DECIMAL(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_usdfrom 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_datecreation_sourceactive_ads: the number of distinct active adsactive_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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task looks like a plain join-and-group-by, but the correctness hinges on table grain.
ad_impressionshas many rows per(ad, day).ad_revenue_eventsalso has many rows per(ad, day).- The metric needs one answer per
(day, creation_source).
If you join the two raw fact tables on ad_id and date, each revenue event is repeated once for every impression that ad had that day. An ad with 1,000 impressions and a $5 revenue event would contribute $5,000. This join fan-out is the central trap.
Key idea
Collapse both fact tables to the same grain, (ad_id, day), and only then join them.
- Active ad-days:
SELECT DISTINCT ad_id, date(impression_time). Exactly one row per active ad per day. - Revenue ad-days:
SUM(revenue_usd) GROUP BY ad_id, date(event_time). At most one row per ad per day. - Use active ad-days as the driving table, join
adsforcreation_source, and LEFT JOIN the revenue on(ad_id, report_date). - Aggregate by
(report_date, creation_source).
Both sides are unique on (ad_id, report_date), so the join is at most one-to-one and cannot multiply revenue.
SQL
WITH active_ad_days AS (
SELECT DISTINCT
i.ad_id,
CAST(i.impression_time AS DATE) AS report_date
FROM ad_impressions i
WHERE i.impression_time >= :start_date
AND i.impression_time < :end_date + INTERVAL '1' DAY
),
revenue_ad_days AS (
SELECT
e.ad_id,
CAST(e.event_time AS DATE) AS report_date,
SUM(e.revenue_usd) AS revenue_usd
FROM ad_revenue_events e
WHERE e.event_time >= :start_date
AND e.event_time < :end_date + INTERVAL '1' DAY
GROUP BY e.ad_id, CAST(e.event_time AS DATE)
)
SELECT
a.report_date,
COALESCE(ad.creation_source, 'UNKNOWN') AS creation_source,
COUNT(DISTINCT a.ad_id) AS active_ads,
COALESCE(SUM(r.revenue_usd), 0) AS active_ad_revenue_usd
FROM active_ad_days a
JOIN ads ad
ON ad.ad_id = a.ad_id
LEFT JOIN revenue_ad_days r
ON r.ad_id = a.ad_id
AND r.report_date = a.report_date
GROUP BY a.report_date, COALESCE(ad.creation_source, 'UNKNOWN')
ORDER BY a.report_date, creation_source;
Why it is correct
- Active definition. Only ad-days with at least one impression exist in the driving table, so nothing else can appear in the output.
- Revenue restriction. Revenue attaches only through a match on the same
(ad_id, report_date). Revenue earned on a day with no impressions has no partner row and is dropped, as the definition requires. - No double counting. Each revenue total is attached to exactly one active ad-day.
COUNT(DISTINCT a.ad_id)equalsCOUNT(*)here, but the DISTINCT documents intent and protects against a future change of grain. - Active but zero revenue. The LEFT JOIN keeps the ad, so it counts in
active_ads.SUMignores the NULL, and the outerCOALESCEconverts an all-NULL group to 0.
Complexity
Let I be impressions in range, R revenue events in range, and A distinct active ad-days.
- Time: O(I + R) for scanning and hash-aggregating, plus roughly O(A) for the join and final grouping. On date-partitioned tables the range predicate prunes partitions, so only the requested days are read.
- Space: O(A + revenue ad-days) for the intermediate results, much smaller than raw impressions.
Edge cases to mention
- Inclusive end date.
BETWEEN :start_date AND :end_dateon timestamps treats the end date as midnight and loses nearly the whole last day. Use< :end_date + 1 day. Keeping the raw column unwrapped in the WHERE clause also preserves index and partition use. - Timezone. Data is UTC, so a plain cast to date is correct. If it were stored in local time, convert first.
- NULL
creation_source. It would form its own group with unpredictable ordering. Bucketing as'UNKNOWN'is reasonable, but state the choice. - Revenue without impressions (late attribution, adjustments). Excluded by definition. Worth confirming that this is the intended business behavior.
- Negative revenue (refunds, credits). Summed as is. Raise it as a product question.
- Empty days or sources. No row is produced. If a dashboard needs a dense grid, cross join a date spine with the distinct sources and LEFT JOIN this result, wrapping measures in
COALESCE(..., 0). - Paid ads. The schema has no paid flag, so assume all rows in
adsqualify. With a flag, filter in theadsjoin.
Common mistakes
SELECT DATE(i.impression_time), a.creation_source,
COUNT(DISTINCT a.ad_id), SUM(e.revenue_usd)
FROM ads a
JOIN ad_impressions i ON i.ad_id = a.ad_id
JOIN ad_revenue_events e ON e.ad_id = a.ad_id
AND DATE(e.event_time) = DATE(i.impression_time)
GROUP BY 1, 2;
- Revenue is multiplied by the number of impressions per ad per day.
- Inner joins drop active ads that earned nothing, so
active_adsis undercounted. - Using
BETWEENon timestamps for the date range loses the last day.
Python equivalent
If asked for pandas, the same grain alignment applies:
import pandas as pd
def active_ad_revenue(ads, impressions, revenue, start_date, end_date):
start = pd.Timestamp(start_date)
end = pd.Timestamp(end_date) + pd.Timedelta(days=1)
imp = impressions[(impressions.impression_time >= start) &
(impressions.impression_time < end)]
active = (imp.assign(report_date=imp.impression_time.dt.normalize())
[["ad_id", "report_date"]]
.drop_duplicates())
rev = revenue[(revenue.event_time >= start) & (revenue.event_time < end)]
rev_daily = (rev.assign(report_date=rev.event_time.dt.normalize())
.groupby(["ad_id", "report_date"], as_index=False)
.revenue_usd.sum())
df = (active.merge(ads[["ad_id", "creation_source"]], on="ad_id")
.merge(rev_daily, on=["ad_id", "report_date"], how="left"))
df["creation_source"] = df["creation_source"].fillna("UNKNOWN")
df["revenue_usd"] = df["revenue_usd"].fillna(0)
out = (df.groupby(["report_date", "creation_source"], as_index=False)
.agg(active_ads=("ad_id", "nunique"),
active_ad_revenue_usd=("revenue_usd", "sum"))
.sort_values(["report_date", "creation_source"]))
return out
The pattern is the same: deduplicate to ad-days, pre-aggregate revenue to ad-days, left-merge, then group.