Rolling Window Metrics and Multi-Role Activity Analysis
SQL & DataAuto-gradedLast updated
Build SQL queries to calculate rolling 7-day caller engagement rates and single-day participation thresholds for geo-filtered active users.
You have two tables representing activity in a voice communication platform:
users
user_idBIGINTcountry_codeSTRING
calls
call_idBIGINTcaller_idBIGINT (referencesusers.user_id)recipient_idBIGINT (referencesusers.user_id)started_atTIMESTAMP
All timestamps in the calls table are recorded in UTC. For reporting purposes, all date-based calculations must use the Europe/London timezone.
Write a SQL query that produces daily metrics with the following columns:
report_date: a calendar date in the London timezonepct_callers_20plus_last_7d: percentage of users who placed 20 or more calls during the 7-day period ending on (and including)report_date- Numerator: count of distinct users who initiated ≥ 20 calls in the 7-day window
- Denominator: count of distinct users who initiated ≥ 1 call in the same 7-day window
pct_gb_dau_50plus_calls: percentage of Great Britain daily active users who participated in 50 or more calls onreport_date- Restrict to users where
country_code = 'GB' - A user is active on a given day if they either placed or received at least one call that day
- Count total participations for each active user, where a participation is either being the caller or being the recipient
- Numerator: count of active GB users with ≥ 50 participations on
report_date - Denominator: count of all active GB users on
report_date
- Restrict to users where
Return one row per report_date, ordered chronologically.
Hints
Hint 1
Convert timestamps to the London timezone before extracting the date—DST transitions mean a UTC midnight does not align with a London day boundary
Hint 2
For rolling windows over distinct users, generate a calendar of dates and join to pre-aggregated daily counts rather than using row-based window functions
Hint 3
Counting participations across both caller and recipient roles requires combining two views of the same call event
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem has three core challenges: timezone-aware date extraction, computing a rolling metric over a sliding window of days, and counting user activity across multiple roles in the same event.
1. Timezone Conversion
Timestamps are stored in UTC but metrics are defined using London calendar days. During British Summer Time (late March through late October), London is UTC+1, so a call at 2024-06-15 23:15:00 UTC belongs to 2024-06-16 in London. Converting the timestamp to the London timezone before truncating to a date is essential. Extracting DATE(started_at) directly from UTC produces incorrect results.
2. Rolling 7-Day Window for Callers
The first metric requires counting distinct users who made at least 20 calls in a 7-day trailing window. A window function like SUM(...) OVER (PARTITION BY caller_id ORDER BY call_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) does not work here because it only produces rows on days when the user was active. If a user made 25 calls over six consecutive days and none on day seven, the metric still needs to report that user for day seven.
The solution is to build a date spine (a complete sequence of report dates) and join it to daily per-user call counts using a range condition: call_date BETWEEN report_date - 6 AND report_date. This expands each user-day into up to seven report-date rows, then aggregates to count distinct users per report date who meet the threshold.
3. Participation Counting Across Roles
The second metric counts participations, where each call generates one participation for the caller and one for the recipient. The correct approach is to unpivot the calls table using UNION ALL:
- One row per call with
caller_idasuser_id - One row per call with
recipient_idasuser_id
This doubles the row count but correctly reflects that each call involves two people. A common mistake is using UNION (which deduplicates), or trying to count with CASE expressions, both of which fail when the same user has multiple calls in a day.
Solution (PostgreSQL)
WITH calls_london AS (
SELECT
call_id,
caller_id,
recipient_id,
CAST((started_at AT TIME ZONE 'UTC') AT TIME ZONE 'Europe/London' AS DATE) AS call_date
FROM calls
),
date_spine AS (
SELECT CAST(d AS DATE) AS report_date
FROM generate_series(
(SELECT MIN(call_date) FROM calls_london),
(SELECT MAX(call_date) FROM calls_london),
INTERVAL '1 day'
) AS g(d)
),
-- Metric 1: daily outgoing call counts per caller
caller_counts_daily AS (
SELECT
caller_id,
call_date,
COUNT(*) AS daily_calls
FROM calls_london
GROUP BY caller_id, call_date
),
caller_rolling_7d AS (
SELECT
ds.report_date,
ccd.caller_id,
SUM(ccd.daily_calls) AS calls_in_window
FROM date_spine ds
JOIN caller_counts_daily ccd
ON ccd.call_date BETWEEN ds.report_date - 6 AND ds.report_date
GROUP BY ds.report_date, ccd.caller_id
),
metric1 AS (
SELECT
report_date,
COUNT(*) AS total_callers,
COUNT(*) FILTER (WHERE calls_in_window >= 20) AS callers_20_plus
FROM caller_rolling_7d
GROUP BY report_date
),
-- Metric 2: participation counts for GB users
all_participations AS (
SELECT caller_id AS user_id, call_date FROM calls_london
UNION ALL
SELECT recipient_id AS user_id, call_date FROM calls_london
),
gb_user_activity AS (
SELECT
ap.call_date AS report_date,
ap.user_id,
COUNT(*) AS participation_count
FROM all_participations ap
INNER JOIN users u
ON u.user_id = ap.user_id
AND u.country_code = 'GB'
GROUP BY ap.call_date, ap.user_id
),
metric2 AS (
SELECT
report_date,
COUNT(*) AS gb_dau,
COUNT(*) FILTER (WHERE participation_count >= 50) AS gb_dau_50_plus
FROM gb_user_activity
GROUP BY report_date
)
SELECT
ds.report_date,
ROUND(100.0 * m1.callers_20_plus / NULLIF(m1.total_callers, 0), 2) AS pct_callers_20plus_last_7d,
ROUND(100.0 * m2.gb_dau_50_plus / NULLIF(m2.gb_dau, 0), 2) AS pct_gb_dau_50plus_calls
FROM date_spine ds
LEFT JOIN metric1 m1 ON m1.report_date = ds.report_date
LEFT JOIN metric2 m2 ON m2.report_date = ds.report_date
ORDER BY ds.report_date;
Complexity
Let C = total calls, U = distinct callers, D = distinct call dates, and R = number of report dates.
- Time: Converting timestamps and aggregating daily counts is O(C). The spine join produces O(U·D) rows before the join and O(7·U·D) rows after (since each user-day can match up to 7 report dates). Final aggregation is O(R). Participation unpivot is O(C), producing 2C rows. Overall: O(C + U·D·R).
- Space: O(U·D + C) for intermediate aggregates.
In practice, pre-aggregating to daily counts before the spine join is critical. Joining raw calls (C rows) to the spine would produce O(7·C) intermediate rows, which is far larger.
Key Edge Cases
- Days with zero calls: The date spine ensures these days appear in the output. Metric 1 may still have values from the trailing window, while metric 2 will be NULL (0/0).
- DST transitions: London days can have 23 or 25 hours. Using the named timezone
Europe/Londonhandles this correctly; a fixed offset like+01:00does not. - Self-calls (caller_id = recipient_id): The
UNION ALLcounts these as two participations. If the requirement is one participation per unique user per call, aggregate withCOUNT(DISTINCT call_id)instead. - Early report dates: The first six days have incomplete 7-day windows. Depending on requirements, you may want to filter
WHERE report_date >= MIN(call_date) + 6. - Missing or NULL country codes: The inner join on
country_code = 'GB'excludes these users from metric 2, which is the intended behavior.
Common Mistakes
- Using
DATE(started_at)directly: Produces incorrect dates during DST. - Window functions over raw calls: Cannot produce rows for days when a user was inactive, breaking the rolling window logic.
- Using
UNIONinstead ofUNION ALL: Collapses duplicate user-day pairs, undercounting participations. - Forgetting
NULLIFin division: Causes division-by-zero errors on days with no activity. - Applying country filter to metric 1: The first metric is for all callers, not just GB users.