Hourly Click-Through Rate and Local Revenue by Country
SQL & DataModel answerLast updated
Calculate hourly CTR and currency-adjusted revenue per country from event logs, joining latest exchange rates and handling time bucketing and safe division.
You're building analytics for a multi-region advertising platform. Two datasets are available:
events table:
event_id(int)user_id(int)event_type(string: either 'view' or 'click')event_timestamp(datetime)revenue_usd(float, non-zero only when event_type is 'click', otherwise 0)country_code(string)
currency_rates table:
country_code(string)currency_code(string)conversion_rate_to_usd(float, representing how many USD equal one unit of local currency)effective_date(date)
Write a SQL query that produces these metrics grouped by hour and country:
- CTR (click-through rate): clicks divided by views. If there are zero views, report 0.
- Total revenue in local currency: sum all revenue and convert using the most recent exchange rate available for each country.
Requirements:
- Only include events from the past 7 days.
- Round timestamps down to the hour (e.g., all events between 14:00:00 and 14:59:59 belong to hour 14:00:00).
- If no exchange rate exists for a country, assume a rate of 1.0.
- Output columns:
hour,country_code,ctr,total_revenue_local.
Example:
Given events:
(1, 101, 'view', '2023-10-01 14:05:00', 0, 'CA')
(2, 101, 'click', '2023-10-01 14:10:00', 5.0, 'CA')
And rate:
('CA', 'CAD', 0.75, '2023-10-01')
The output should be:
hour | country_code | ctr | total_revenue_local
2023-10-01 14:00:00 | CA | 1.0 | 6.67
Explanation: One view and one click gives CTR = 1.0. Since 1 CAD = 0.75 USD, converting 5 USD to CAD means 5 / 0.75 ≈ 6.67 CAD.
Hints
Hint 1
Use window functions to find the latest exchange rate per country before joining to avoid row duplication
Hint 2
Apply DATE_TRUNC or similar to bucket timestamps into hourly intervals
Hint 3
Protect against division by zero when computing CTR and handle null or zero exchange rates
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines time bucketing, conditional aggregation, and a join pattern that requires careful handling to avoid duplicating rows. The solution breaks down into three logical stages:
- Identify the latest exchange rate per country using a window function.
- Aggregate events by hour and country, counting views and clicks separately and summing revenue.
- Join rates to aggregated data and compute CTR and converted revenue with safe arithmetic.
Step 1: Latest Exchange Rate per Country
Multiple rates may exist for a country with different effective_date values. We need exactly one rate per country—the most recent—to avoid row explosion during the join.
Use ROW_NUMBER() to rank rates by effective_date DESC within each country, keeping only the top row:
WITH latest_rates AS (
SELECT country_code, conversion_rate_to_usd
FROM (
SELECT
country_code,
conversion_rate_to_usd,
ROW_NUMBER() OVER (
PARTITION BY country_code
ORDER BY effective_date DESC
) AS rn
FROM currency_rates
WHERE effective_date <= CURRENT_DATE
) r
WHERE rn = 1
)
Why ROW_NUMBER() and not RANK() or a self-join with MAX(effective_date)? Both alternatives can return multiple rows per country if there are ties, which would multiply revenue when joined. ROW_NUMBER() guarantees exactly one row per partition.
Step 2: Aggregate Events by Hour and Country
Filter events to the trailing 7 days, bucket timestamps to the hour, and use conditional aggregation to count views and clicks in one pass:
hourly AS (
SELECT
DATE_TRUNC('hour', event_timestamp) AS hour,
country_code,
SUM(CASE WHEN event_type = 'view' THEN 1 ELSE 0 END) AS views,
SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) AS clicks,
SUM(CASE WHEN event_type = 'click' THEN COALESCE(revenue_usd, 0) ELSE 0 END) AS revenue_usd
FROM events
WHERE event_timestamp >= CURRENT_TIMESTAMP - INTERVAL '7 days'
AND event_timestamp < CURRENT_TIMESTAMP
GROUP BY 1, 2
)
Key details:
DATE_TRUNC('hour', ...)floors timestamps to the hour boundary.- Revenue is summed only for click events; views contribute zero.
- Aggregating before joining is more efficient and avoids double-counting.
Step 3: Compute CTR and Local Revenue
Join the aggregated events to the latest rates and apply the formulas:
SELECT
h.hour,
h.country_code,
COALESCE(h.clicks::DOUBLE PRECISION / NULLIF(h.views, 0), 0) AS ctr,
h.revenue_usd / COALESCE(NULLIF(r.conversion_rate_to_usd, 0), 1.0) AS total_revenue_local
FROM hourly h
LEFT JOIN latest_rates r
ON h.country_code = r.country_code
ORDER BY h.hour, h.country_code;
CTR calculation:
- Cast
clicksto double to avoid integer division. - Use
NULLIF(views, 0)to turn zero denominators intoNULL, thenCOALESCE(..., 0)to meet the spec requirement that zero-view hours have CTR = 0.
Currency conversion:
- The column name
conversion_rate_to_usdindicates how much USD one unit of local currency equals. To convert USD to local currency, divide by the rate. (If the rate is 0.75, meaning 1 CAD = 0.75 USD, then 5 USD = 5 / 0.75 = 6.67 CAD.) - Wrap the rate in
NULLIF(..., 0)to guard against zero rates, thenCOALESCE(..., 1.0)to handle missing rates. - Use a
LEFT JOINso countries without rates are retained.
Complete Solution (PostgreSQL)
WITH latest_rates AS (
SELECT country_code, conversion_rate_to_usd
FROM (
SELECT
country_code,
conversion_rate_to_usd,
ROW_NUMBER() OVER (
PARTITION BY country_code
ORDER BY effective_date DESC
) AS rn
FROM currency_rates
WHERE effective_date <= CURRENT_DATE
) r
WHERE rn = 1
),
hourly AS (
SELECT
DATE_TRUNC('hour', event_timestamp) AS hour,
country_code,
SUM(CASE WHEN event_type = 'view' THEN 1 ELSE 0 END) AS views,
SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) AS clicks,
SUM(CASE WHEN event_type = 'click' THEN COALESCE(revenue_usd, 0) ELSE 0 END) AS revenue_usd
FROM events
WHERE event_timestamp >= CURRENT_TIMESTAMP - INTERVAL '7 days'
AND event_timestamp < CURRENT_TIMESTAMP
GROUP BY 1, 2
)
SELECT
h.hour,
h.country_code,
COALESCE(h.clicks::DOUBLE PRECISION / NULLIF(h.views, 0), 0) AS ctr,
h.revenue_usd / COALESCE(NULLIF(r.conversion_rate_to_usd, 0), 1.0) AS total_revenue_local
FROM hourly h
LEFT JOIN latest_rates r
ON h.country_code = r.country_code
ORDER BY h.hour, h.country_code;
Complexity
Time: O(N) to scan and aggregate the 7-day slice of events, plus O(R log R) to sort and rank rates (typically negligible since R is small—one row per country per rate change).
Space: O(H × C) for the hourly aggregates, where H ≈ 168 hours and C is the number of distinct countries, plus O(C) for the deduplicated rates.
Edge Cases and Trade-offs
- Clicks without views in an hour: CTR could exceed 1.0 if users click multiple times or if view events are lost. The spec says to report the ratio as computed, but in production you'd flag this anomaly.
- Missing currency rates: Defaulting to 1.0 assumes local currency = USD. Confirm this fallback with stakeholders.
- Time zones:
DATE_TRUNCoperates in the timestamp's stored time zone (usually UTC). If "hour" should be local to each country, you'd need a country-to-timezone mapping and applyAT TIME ZONE. - Sparse hours: Hours with no events produce no row. If a dense time series is required, generate a spine of all hour × country combinations and left-join the aggregates.
- Dialect differences: For Presto/Trino, use
date_trunc(...),INTERVAL '7' DAY, andCAST(clicks AS DOUBLE). For BigQuery, useTIMESTAMP_TRUNC(..., HOUR)andDATE_SUB(...).
Common Mistakes
- Using
RANK()orMAX(effective_date)self-join for rates. Both can return multiple rows per country if there are ties, inflating revenue. - Multiplying by the conversion rate instead of dividing. The column name indicates the rate is "to USD," so local = USD / rate.
- Integer division. Forgetting to cast to float/double causes CTR to round to 0 or 1.
- Joining before aggregating. This multiplies event rows if there are duplicate rates, producing incorrect sums.
- Ignoring future-dated rates. Rates with
effective_datebeyond today should be excluded to avoid applying rates not yet in effect.