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_streamed whose time_minute is non-null represents exactly 1 minute of broadcast time by streamer_username (regardless of concurrent_viewers). Ignore any row where time_minute IS NULL.
  • Multi-year calendar months: Extract integer year (e.g., 2021) and integer month (1 through 12) 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.0 using 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 generate 0-hour rows for silent months), ordered ascending by year first and month second.

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

  • year and month must be returned as integers (1 <= month <= 12).
  • total_hours must be rounded to 4 decimal places (ROUND(..., 4)).
  • Output columns must be year, month, total_hours, sorted strictly by year ASC, month ASC.

Step-by-step walkthrough

  1. 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 is COUNT(*) / 60.0, rounded to 4 decimal places.
    • concurrent_viewers records audience size during that minute rather than broadcast duration, so it does not affect total_hours.
    • We return (year, month, total_hours) with integer year, integer month, and rounded total_hours, sorted chronologically by year, then month, omitting inactive months.
  2. Two classic multi-year traps to avoid

    When data spans multiple years (such as 2020 through 2022), two beginner mistakes break monthly reports:

    1. Grouping by month alone (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).
    2. Sorting unpadded month strings ('1', '2', ..., '10'): in text order, '10' comes before '9' because '1' < '9'. Storing year and month as INTEGER ensures ORDER BY year, month compares 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
    
  3. 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 calendar year and month as integers:

    • In SQLite, strftime('%Y', time_minute) extracts the 4-digit year as text ('2022') and strftime('%m', time_minute) extracts the month ('02'). Wrapping each in CAST(... AS INTEGER) produces clean integers 2022 and 2. (In PostgreSQL, BigQuery, or Snowflake, the equivalent is EXTRACT(YEAR FROM time_minute) and EXTRACT(MONTH FROM time_minute).)
    • WHERE time_minute IS NOT NULL drops 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
    )
    
  4. Count minutes per calendar month and convert to hours

    Next, we group streamed_minutes by (year, month) and convert the row count from minutes into hours:

    • Why 60.0 instead of 60: 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 = 0 and 5 / 60 = 0!). Dividing by 60.0 forces floating-point division (5 / 60.0 = 0.083333...).
    • ROUND(..., 4): rounds total_hours to the required 4 decimal places (0.0833).
    • Because GROUP BY only 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
    
  5. Sort chronologically across multiple years

    SQL's GROUP BY does not guarantee output row order, and chronological order is explicitly required here. Adding ORDER BY year, month sorts by integer year ascending first, and by integer month 1..12 ascending 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, month
    
  6. Trace on Example 1

    Let's trace the eight rows of minute_streamed in 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.0833
    

    Even though the first row in the input was from 2022-02, ORDER BY year, month places (2021, 11, 0.05) ahead of (2022, 2, 0.0833).

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

  1. Extract (year, month) as integers: the 3 November timestamps map to (2021, 11) and the 5 February timestamps map to (2022, 2).
  2. Group by (year, month): (2021, 11) counts 3 minutes across pixel and nova; (2022, 2) counts 5 minutes across nova and echo.
  3. Convert to hours and round: 3 / 60.0 = 0.05 and 5 / 60.0 = 0.083333..., which ROUND(..., 4) formats to 0.0833.
  4. Sort chronologically: ORDER BY year, month outputs (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 N rows once to extract year and month, aggregate them into M monthly buckets in O(N) average time using hash aggregation (or O(N log N) if the engine sorts to group), and sort the M monthly summary rows in O(M log M) time. Since M is tiny compared to N, total runtime is linear O(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 because streamer_username, category, and concurrent_viewers are 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 to 1,440 minute 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 month to INTEGER ensures 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.
  • NULL timestamps: excluded by WHERE time_minute IS NOT NULL so missing timestamps never create a (NULL, NULL) row.
  • Empty minute_streamed table: 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 60 instead of 60.0: in SQLite, PostgreSQL, and SQL Server, COUNT(*) / 60 truncates toward zero, turning any sub-hour month (like Example 1's 3 and 5 minutes!) into 0.
  • Sorting unpadded string months: CAST(month AS TEXT) sorts '10', '11', '12' ahead of '2' through '9'.
  • Summing concurrent_viewers instead of counting rows: SUM(concurrent_viewers) / 60.0 measures total viewer-hours watched, not creator hours broadcast.
  • Omitting ORDER BY year, month: SQL does not promise sorted output from GROUP 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_streamed by streamer_username, compute COUNT(*) / 60.0 for total hours, and use conditional aggregation (SUM(CASE WHEN ... THEN 1 ELSE 0 END) inside the same GROUP BY) to count minutes where UPPER(category) LIKE '%' || UPPER(:keyword) || '%'. Wrapping both sides in UPPER(...) makes substring matching case-insensitive across every SQL dialect (if :keyword could contain literal % or _, use INSTR(UPPER(category), UPPER(:keyword)) > 0 instead). On Example 1 with :keyword = 'speed', nova has 3 of 4 minutes in 'Speedruns' (0.0667 hours, 75.0%), while pixel (0.0333 hours) and echo (0.0333 hours) each get 0.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 timeline month_index = year * 12 + month so January 2022 (24266) is 1 higher than December 2021 (24265). Then apply LAG (a window function that reads a column's value from the previous row in the same partition without collapsing rows) partitioned by streamer_username and ordered by month_index. If prev_index = month_index - 1, check hours > prev_hours; if prev_index < month_index - 1, there was at least one silent 0-hour month in between (like nova jumping from 2021-11 to 2022-02 in Example 1), so any positive hours > 0 after the gap exceeds 0 (requiring prev_index IS NOT NULL avoids 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_streamed directly to minute_viewed multiplies every streamed minute by all its viewer rows, distorting both AVG(concurrent_viewers) and COUNT(*)): filter both tables with time_minute >= '2019-01-01' AND time_minute < '2020-01-01', compute SUM(CASE WHEN viewer_country = 'US' THEN 1 ELSE 0 END) in minute_viewed, and LEFT JOIN both summaries onto the UNION of 2019 creators. To emit 0.0 hours for silent months between MIN(time_minute) and MAX(time_minute), generate a month-start calendar spine with a recursive CTE (DATE(month_start, '+1 month'), guarded by HAVING COUNT(*) > 0 for empty tables) and LEFT JOIN the monthly counts with COALESCE(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

Similar questions

More Twitch interview questions

All 5 Twitch questions →