Chronological Broadcast Hours per Calendar Month
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
A live-video broadcasting service records telemetry at one-minute granularity: every minute a creator is live on air appends one row to minute_streamed.
Write a SQL query to calculate the total broadcast hours (total_hours) across the entire platform for each active calendar month, sorted in chronological order.
Follow these exact rules:
- One row equals one broadcast minute: Every row in
minute_streamedwhosetime_minuteis non-null represents exactly 1 minute of broadcast time bystreamer_username(regardless ofconcurrent_viewers). Ignore any row wheretime_minute IS NULL. - Multi-year calendar months: Extract integer
year(e.g.,2021) and integermonth(1through12) so the same month number in different years stays in separate monthly buckets. - Hours conversion and precision: Convert each month's total broadcast minutes into hours by dividing by
60.0using floating-point division and rounding to 4 decimal places (ROUND(..., 4)). - Active months and chronological ordering: Emit rows only for calendar months that have at least one valid row in
minute_streamed(do not generate0-hour rows for silent months), ordered ascending byyearfirst andmonthsecond.
Input Schema
minute_streamed
| Column | Type | Description |
|---|---|---|
time_minute |
TIMESTAMP |
Minute timestamp ('YYYY-MM-DD HH:MM:SS') of the broadcast |
streamer_username |
VARCHAR |
Handle of the broadcasting creator |
category |
VARCHAR |
Broadcast topic or game directory |
concurrent_viewers |
INTEGER |
Audience size watching during that minute |
Examples
Example 1
Input:
minute_streamed
time_minute |
streamer_username |
category |
concurrent_viewers |
|---|---|---|---|
| 2022-02-14 19:00:00 | nova | Speedruns | 210 |
| 2021-11-08 14:20:00 | pixel | ArtStudio | 85 |
| 2021-11-08 14:21:00 | pixel | ArtStudio | 92 |
| 2021-11-25 20:45:00 | nova | Tabletop | 140 |
| 2022-02-14 19:01:00 | nova | Speedruns | 225 |
| 2022-02-14 19:02:00 | nova | Speedruns | 218 |
| 2022-02-28 23:58:00 | echo | SynthLive | 60 |
| 2022-02-28 23:59:00 | echo | SynthLive | 64 |
Output:
year |
month |
total_hours |
|---|---|---|
| 2021 | 11 | 0.05 |
| 2022 | 2 | 0.0833 |
Explanation:
- November 2021 (year = 2021, month = 11) has 3 streamed minutes across pixel and nova: 3 / 60.0 = 0.05 hours.
- December 2021 and January 2022 have no rows and are omitted.
- February 2022 (year = 2022, month = 2) has 5 streamed minutes across nova and echo: 5 / 60.0 = 0.083333..., rounded to 0.0833.
Example 2
Input:
minute_streamed
time_minute |
streamer_username |
category |
concurrent_viewers |
|---|---|---|---|
| 2021-09-03 10:15:00 | kestrel | Strategy | 50 |
| 2020-10-12 08:00:00 | kestrel | Strategy | 40 |
| 2020-10-12 08:01:00 | kestrel | Strategy | 42 |
| 2020-09-30 23:59:00 | lyric | Acoustic | 30 |
| NULL | lyric | Acoustic | 12 |
Output:
year |
month |
total_hours |
|---|---|---|
| 2020 | 9 | 0.0167 |
| 2020 | 10 | 0.0333 |
| 2021 | 9 | 0.0167 |
Explanation:
The NULL timestamp row is ignored. September 2020 (2020, 9) sorts numerically before October 2020 (2020, 10), and September 2021 (2021, 9) stays in its own bucket rather than merging with September 2020.
Constraints
yearandmonthmust be returned as integers (1 <= month <= 12).total_hoursmust be rounded to 4 decimal places (ROUND(..., 4)).- Output columns must be
year,month,total_hours, sorted strictly byyear ASC, month ASC.
Step-by-step walkthrough
Restate the goal and table grain
Before writing any SQL, always check the grain of the table — what a single row represents:
- In
minute_streamed(time_minute, streamer_username, category, concurrent_viewers), each valid row represents 1 broadcast minute by one creator. - Therefore, total broadcast minutes in a calendar month is simply
COUNT(*)(the number of non-null rows in that month), and total broadcast hours isCOUNT(*) / 60.0, rounded to 4 decimal places. concurrent_viewersrecords audience size during that minute rather than broadcast duration, so it does not affecttotal_hours.- We return
(year, month, total_hours)with integeryear, integermonth, and roundedtotal_hours, sorted chronologically byyear, thenmonth, omitting inactive months.
- In
Two classic multi-year traps to avoid
When data spans multiple years (such as
2020through2022), two beginner mistakes break monthly reports:- Grouping by
monthalone (GROUP BY month): September 2020 (month = 9) and September 2021 (month = 9) collapse into a single row instead of staying two distinct calendar months! You must group by the pair(year, month). - Sorting unpadded month strings (
'1','2', ...,'10'): in text order,'10'comes before'9'because'1' < '9'. StoringyearandmonthasINTEGERensuresORDER BY year, monthcompares numbers (9 < 10, and(2021, 11)before(2022, 2)).
Text sort (WRONG): '1', '10', '11', '12', '2', ..., '9' Integer sort (RIGHT): 1, 2, ..., 9, 10, 11, 12- Grouping by
Extract integer year and month per broadcast minute
We start with a Common Table Expression (CTE) — a named temporary step written
WITH streamed_minutes AS (...)— that extracts each row's calendaryearandmonthas integers:- In SQLite,
strftime('%Y', time_minute)extracts the 4-digit year as text ('2022') andstrftime('%m', time_minute)extracts the month ('02'). Wrapping each inCAST(... AS INTEGER)produces clean integers2022and2. (In PostgreSQL, BigQuery, or Snowflake, the equivalent isEXTRACT(YEAR FROM time_minute)andEXTRACT(MONTH FROM time_minute).) WHERE time_minute IS NOT NULLdrops any malformed row missing a timestamp so it does not create a bogus(NULL, NULL)group.
WITH streamed_minutes AS ( -- Extract calendar year and month as integers for each valid streamed-minute row. -- Skipping NULL timestamps prevents an artificial (NULL, NULL) month bucket. SELECT CAST(strftime('%Y', time_minute) AS INTEGER) AS year, CAST(strftime('%m', time_minute) AS INTEGER) AS month FROM minute_streamed WHERE time_minute IS NOT NULL )- In SQLite,
Count minutes per calendar month and convert to hours
Next, we group
streamed_minutesby(year, month)and convert the row count from minutes into hours:- Why
60.0instead of60:COUNT(*)returns an integer. In SQLite, PostgreSQL, and SQL Server, dividing an integer by an integer (COUNT(*) / 60) performs integer division, which chops off the decimal fraction (3 / 60 = 0and5 / 60 = 0!). Dividing by60.0forces floating-point division (5 / 60.0 = 0.083333...). ROUND(..., 4): roundstotal_hoursto the required 4 decimal places (0.0833).- Because
GROUP BYonly forms groups from rows that exist, months with zero broadcast activity naturally do not appear.
SELECT year, month, ROUND(COUNT(*) / 60.0, 4) AS total_hours FROM streamed_minutes GROUP BY year, month- Why
Sort chronologically across multiple years
SQL's
GROUP BYdoes not guarantee output row order, and chronological order is explicitly required here. AddingORDER BY year, monthsorts by integer year ascending first, and by integer month1..12ascending within each year:-- Group by (year, month) together so multi-year data keeps March 2019 separate from March 2020. -- Divide COUNT(*) by 60.0 (float, not integer 60) to convert streamed minutes into hours, -- and sort integer year then month for true chronological order. SELECT year, month, ROUND(COUNT(*) / 60.0, 4) AS total_hours FROM streamed_minutes GROUP BY year, month ORDER BY year, monthTrace on Example 1
Let's trace the eight rows of
minute_streamedin Example 1:Input rows -> streamed_minutes CTE: time_minute | streamer | category | viewers || year | month --------------------+----------+-----------+---------++------+------ 2022-02-14 19:00:00 | nova | Speedruns | 210 || 2022 | 2 2021-11-08 14:20:00 | pixel | ArtStudio | 85 || 2021 | 11 2021-11-08 14:21:00 | pixel | ArtStudio | 92 || 2021 | 11 2021-11-25 20:45:00 | nova | Tabletop | 140 || 2021 | 11 2022-02-14 19:01:00 | nova | Speedruns | 225 || 2022 | 2 2022-02-14 19:02:00 | nova | Speedruns | 218 || 2022 | 2 2022-02-28 23:58:00 | echo | SynthLive | 60 || 2022 | 2 2022-02-28 23:59:00 | echo | SynthLive | 64 || 2022 | 2 Grouped & ordered by (year, month): year | month | COUNT(*) (minutes) | COUNT(*) / 60.0 | ROUND(..., 4) -----+-------+--------------------+-----------------+-------------- 2021 | 11 | 3 | 0.05 | 0.05 2022 | 2 | 5 | 0.083333... | 0.0833Even though the first row in the input was from
2022-02,ORDER BY year, monthplaces(2021, 11, 0.05)ahead of(2022, 2, 0.0833).Complete query
WITH streamed_minutes AS ( -- Extract calendar year and month as integers for each valid streamed-minute row. -- Skipping NULL timestamps prevents an artificial (NULL, NULL) month bucket. SELECT CAST(strftime('%Y', time_minute) AS INTEGER) AS year, CAST(strftime('%m', time_minute) AS INTEGER) AS month FROM minute_streamed WHERE time_minute IS NOT NULL ) -- Group by (year, month) together so multi-year data keeps March 2019 separate from March 2020. -- Divide COUNT(*) by 60.0 (float, not integer 60) to convert streamed minutes into hours, -- and sort integer year then month for true chronological order. SELECT year, month, ROUND(COUNT(*) / 60.0, 4) AS total_hours FROM streamed_minutes GROUP BY year, month ORDER BY year, month✅ Submit now — all tests should pass.
Intuition & how it works
Picture minute_streamed as a giant shoebox of 1-minute punch cards: every time a creator broadcasts for one minute, the service drops one timestamped card into the box. To report total broadcast hours per calendar month across multiple years, you label cubbyholes with both the year and the month (2020-09, 2020-10, 2021-09, 2022-02), toss each valid punch card into its matching (year, month) cubbyhole, count how many 1-minute cards landed in each cubbyhole, divide by 60.0 to convert minutes into hours, and read the non-empty cubbyholes in calendar order.
A naive query trips over three subtle traps. First, grouping by month number alone (GROUP BY EXTRACT(MONTH FROM time_minute)) merges September 2020 and September 2021 into one bucket whenever the dataset spans more than a year. Second, writing COUNT(*) / 60 triggers integer division (whole-number division that discards the remainder), turning 45 minutes into 0 hours instead of 0.75. Third, summing concurrent_viewers computes viewer-minutes watched rather than broadcast hours, ignoring the table grain (what one row represents — here, exactly 1 broadcast minute).
Using a Common Table Expression (CTE) (a named temporary step WITH streamed_minutes AS (...)), let's walk through Example 1's 8 rows:
- Extract
(year, month)as integers: the 3 November timestamps map to(2021, 11)and the 5 February timestamps map to(2022, 2). - Group by
(year, month):(2021, 11)counts3minutes acrosspixelandnova;(2022, 2)counts5minutes acrossnovaandecho. - Convert to hours and round:
3 / 60.0 = 0.05and5 / 60.0 = 0.083333..., whichROUND(..., 4)formats to0.0833. - Sort chronologically:
ORDER BY year, monthoutputs(2021, 11, 0.05)followed by(2022, 2, 0.0833).
Complexity
Let N be the number of rows in minute_streamed and M be the number of distinct active (year, month) pairs (M <= N, typically a few dozen even across years of history).
- Time: We scan all
Nrows once to extractyearandmonth, aggregate them intoMmonthly buckets inO(N)average time using hash aggregation (orO(N log N)if the engine sorts to group), and sort theMmonthly summary rows inO(M log M)time. SinceMis tiny compared toN, total runtime is linearO(N)with hash aggregation. - Space:
O(M)memory to store one counter per active(year, month)bucket.
Helpful indexes and layout:
- A covering index (an index holding every column needed by the query so the database scans the compact index instead of wide table rows) on
minute_streamed(time_minute)shrinks I/O becausestreamer_username,category, andconcurrent_viewersare never read. - At live-streaming scale (hundreds of millions of minute rows per month), partition pruning (storing data partitioned by date so date-bounded queries skip irrelevant months) plus a daily rollup table
(stream_date, streamer_username, category, minutes_streamed)compresses up to1,440minute rows per creator-day into 1 row.
Edge cases
- Multi-year datasets: grouping and ordering by
(year, month)keeps September 2020 separate from September 2021 and sorts December 2019(2019, 12)before January 2020(2020, 1). - Two-digit vs one-digit months: casting
monthtoINTEGERensures September (9) comes before October (10), avoiding lexicographical'10' < '9'bugs. - Exact month and leap-year boundaries:
'2020-02-29 23:59:00'lands in(2020, 2)while'2020-03-01 00:00:00'lands in(2020, 3). - Months with zero broadcast activity: omitted naturally by
GROUP BY, matching the required output format. NULLtimestamps: excluded byWHERE time_minute IS NOT NULLso missing timestamps never create a(NULL, NULL)row.- Empty
minute_streamedtable: returns 0 rows cleanly.
Common mistakes
- Grouping only by
month: combines the same month across different years into a single inflated total. - Dividing by integer
60instead of60.0: in SQLite, PostgreSQL, and SQL Server,COUNT(*) / 60truncates toward zero, turning any sub-hour month (like Example 1's 3 and 5 minutes!) into0. - Sorting unpadded string months:
CAST(month AS TEXT)sorts'10','11','12'ahead of'2'through'9'. - Summing
concurrent_viewersinstead of counting rows:SUM(concurrent_viewers) / 60.0measures total viewer-hours watched, not creator hours broadcast. - Omitting
ORDER BY year, month: SQL does not promise sorted output fromGROUP BY, even if some engines happen to sort internally.
Follow-up questions
- How would you compute each creator's total broadcast hours alongside the percentage of their broadcast time spent in categories matching a case-insensitive keyword? Group
minute_streamedbystreamer_username, computeCOUNT(*) / 60.0for total hours, and use conditional aggregation (SUM(CASE WHEN ... THEN 1 ELSE 0 END)inside the sameGROUP BY) to count minutes whereUPPER(category) LIKE '%' || UPPER(:keyword) || '%'. Wrapping both sides inUPPER(...)makes substring matching case-insensitive across every SQL dialect (if:keywordcould contain literal%or_, useINSTR(UPPER(category), UPPER(:keyword)) > 0instead). On Example 1 with:keyword = 'speed',novahas 3 of 4 minutes in'Speedruns'(0.0667hours,75.0%), whilepixel(0.0333hours) andecho(0.0333hours) each get0.0%.
sql
SELECT
streamer_username,
ROUND(COUNT(*) / 60.0, 4) AS total_hours,
ROUND(
100.0 * SUM(
CASE WHEN UPPER(category) LIKE '%' || UPPER(:keyword) || '%'
THEN 1 ELSE 0 END
) / COUNT(*),
2
) AS keyword_pct
FROM minute_streamed
WHERE time_minute IS NOT NULL
GROUP BY streamer_username
- How would you list every creator whose broadcast hours in any calendar month strictly exceeded their hours in the immediately preceding calendar month, accounting for year rollovers and inactive zero-hour months? Map every
(year, month)onto a single continuous integer timelinemonth_index = year * 12 + monthso January 2022 (24266) is1higher than December 2021 (24265). Then applyLAG(a window function that reads a column's value from the previous row in the same partition without collapsing rows) partitioned bystreamer_usernameand ordered bymonth_index. Ifprev_index = month_index - 1, checkhours > prev_hours; ifprev_index < month_index - 1, there was at least one silent0-hour month in between (likenovajumping from2021-11to2022-02in Example 1), so any positivehours > 0after the gap exceeds0(requiringprev_index IS NOT NULLavoids treating a creator's debut month as growth).
sql
WITH monthly AS (
SELECT
streamer_username,
CAST(strftime('%Y', time_minute) AS INTEGER) * 12
+ CAST(strftime('%m', time_minute) AS INTEGER) AS month_index,
COUNT(*) / 60.0 AS hours
FROM minute_streamed
WHERE time_minute IS NOT NULL
GROUP BY
streamer_username,
CAST(strftime('%Y', time_minute) AS INTEGER) * 12
+ CAST(strftime('%m', time_minute) AS INTEGER)
),
with_prev AS (
SELECT
streamer_username,
month_index,
hours,
LAG(month_index) OVER (PARTITION BY streamer_username ORDER BY month_index) AS prev_index,
LAG(hours) OVER (PARTITION BY streamer_username ORDER BY month_index) AS prev_hours
FROM monthly
)
SELECT DISTINCT streamer_username
FROM with_prev
WHERE prev_index IS NOT NULL
AND hours > CASE WHEN prev_index = month_index - 1 THEN prev_hours ELSE 0 END
- If a second table minute_viewed(time_minute, viewer_username, viewer_country, streamer_username) logs one row per viewer-minute, how would you report each creator's 2019 average concurrent_viewers and total 2019 minutes watched from 'US' without join fan-out, and how would you fill missing months with 0.0 hours? For 2019 metrics, aggregate each table separately before joining to avoid the fan-out trap (joining
minute_streameddirectly tominute_viewedmultiplies every streamed minute by all its viewer rows, distorting bothAVG(concurrent_viewers)andCOUNT(*)): filter both tables withtime_minute >= '2019-01-01' AND time_minute < '2020-01-01', computeSUM(CASE WHEN viewer_country = 'US' THEN 1 ELSE 0 END)inminute_viewed, andLEFT JOINboth summaries onto theUNIONof 2019 creators. To emit0.0hours for silent months betweenMIN(time_minute)andMAX(time_minute), generate a month-start calendar spine with a recursive CTE (DATE(month_start, '+1 month'), guarded byHAVING COUNT(*) > 0for empty tables) andLEFT JOINthe monthly counts withCOALESCE(s.minutes, 0) / 60.0.
sql
WITH streamed_2019 AS (
SELECT
streamer_username,
AVG(concurrent_viewers) AS avg_viewers
FROM minute_streamed
WHERE time_minute >= '2019-01-01'
AND time_minute < '2020-01-01'
GROUP BY streamer_username
),
viewed_2019 AS (
SELECT
streamer_username,
SUM(CASE WHEN viewer_country = 'US' THEN 1 ELSE 0 END) AS us_minutes
FROM minute_viewed
WHERE time_minute >= '2019-01-01'
AND time_minute < '2020-01-01'
GROUP BY streamer_username
),
creators_2019 AS (
SELECT streamer_username FROM streamed_2019
UNION
SELECT streamer_username FROM viewed_2019
)
SELECT
c.streamer_username,
ROUND(st.avg_viewers, 2) AS avg_concurrent_viewers_2019,
COALESCE(v.us_minutes, 0) AS us_minutes_watched_2019
FROM creators_2019 AS c
LEFT JOIN streamed_2019 AS st
ON st.streamer_username = c.streamer_username
LEFT JOIN viewed_2019 AS v
ON v.streamer_username = c.streamer_username
Follow-up questions
- How would you compute each creator's total broadcast hours alongside the percentage of their broadcast time spent in categories matching a case-insensitive keyword?
- How would you list every creator whose broadcast hours in any calendar month strictly exceeded their hours in the immediately preceding calendar month, accounting for year rollovers and inactive zero-hour months?
- If a second table minute_viewed(time_minute, viewer_username, viewer_country, streamer_username) logs one row per viewer-minute, how would you report each creator's 2019 average concurrent_viewers and total 2019 minutes watched from 'US' without join fan-out, and how would you fill missing months with 0.0 hours?
Similar questions
- Multi-Metric Live Broadcast Telemetry in SQL and Python
- Real-Time Live Broadcast Recommender System
- Role Motivation and Data Science Behavioral Scenarios
- Implement Four Standalone Stateful Coding Utilities
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts