KatInterview

Hourly Click-Through Rate and Local Revenue by Country

SQL & DataModel answer
MediumModel answerSQL & Dataaggregationjoinswindow-functions

Last 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:

  1. CTR (click-through rate): clicks divided by views. If there are zero views, report 0.
  2. 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