Daily First-Viewed Content Share

Easy · Data Manipulation (SQL/Python) · Data Analyst · Technical Screen

Problem Statement

A digital media platform logs every page impression in a page_views table. Editorial analysts want to measure which content format brings each reader onto the site at the start of their daily activity.

Define an agent-day as one unique viewer (agent_id) active on one UTC calendar date (DATE(viewed_at)). For each (agent_id, event_date) pair, locate that viewer's earliest page view on that calendar date (viewed_at ASC, breaking exact timestamp ties by view_id ASC) and take its content_type.

Write a SQL query that computes the daily distribution of these first-viewed content formats across all agent-days, returning four columns:

  • event_date: the UTC calendar date ('YYYY-MM-DD') extracted from viewed_at.
  • content_type: the content_type of the viewer's first page view on event_date.
  • agent_days: how many distinct viewers on event_date had that content_type on their first view of the day.
  • share: agent_days divided by the total agent_days across all content types on event_date, rounded to 4 decimal places.

Input Schema

page_views

Column Type Description
view_id INTEGER Unique identifier of the page-view event
agent_id VARCHAR Viewer identifier
content_id VARCHAR Identifier of the viewed item (NULL on landing or section pages)
url VARCHAR Request path
content_type VARCHAR Format label (such as 'article', 'video', 'podcast', or NULL)
device_type VARCHAR Client form factor ('phone', 'tab', 'desktop')
viewed_at TIMESTAMP UTC event timestamp ('YYYY-MM-DD HH:MM:SS')

Examples

Example 1

Input:

page_views

view_id agent_id content_id url content_type device_type viewed_at
10 v1 art_9 /news/9 article phone 2024-05-10 07:20:00
11 v1 vid_4 /watch/4 video desktop 2024-05-10 11:45:00
12 v2 NULL /front article tab 2024-05-10 06:50:00
13 v2 pod_2 /listen/2 podcast phone 2024-05-10 19:10:00
14 v3 vid_4 /watch/4 video desktop 2024-05-10 14:00:00
15 v1 pod_2 /listen/2 podcast phone 2024-05-11 08:00:00
16 v1 art_9 /news/9 article phone 2024-05-11 08:00:00
17 v2 art_5 /news/5 article desktop 2024-05-11 13:30:00
18 v2 vid_7 /watch/7 video tab 2024-05-11 09:15:00

Output:

event_date content_type agent_days share
2024-05-10 article 2 0.6667
2024-05-10 video 1 0.3333
2024-05-11 podcast 1 0.5
2024-05-11 video 1 0.5

Explanation: - On 2024-05-10, three viewers are active (3 agent-days): v1 starts with 'article' at 07:20:00, v2 starts with 'article' at 06:50:00 (a NULL content_id is still a valid page view), and v3 starts with 'video' at 14:00:00. That produces 2 / 3 = 0.6667 for 'article' and 1 / 3 = 0.3333 for 'video'. - On 2024-05-11, two viewers are active (2 agent-days): v1 has two views tied at 08:00:00, so smaller view_id = 15 ('podcast') wins; v2's earliest timestamp is 09:15:00 (view_id = 18, 'video'), which beats 13:30:00 (view_id = 17) even though 17 < 18. Each format gets 1 / 2 = 0.5.

Constraints

  • Interpret all viewed_at timestamps in UTC; midnight 00:00:00 begins a new event_date.
  • A row with content_id IS NULL still participates in first-view selection.
  • If a viewer's winning first view has content_type IS NULL, report NULL as its own content_type group and include those agent-days in the date's share denominator.
  • Round share to 4 decimal places using floating-point division; output rows may appear in any order.

Step-by-step walkthrough

  1. Understand the goal and output shape

    The building block of this query is an agent-day: one viewer (agent_id) active on one UTC calendar date (DATE(viewed_at)). Even if viewer v1 loads 50 pages on 2024-05-10, v1 contributes one agent-day on 2024-05-10, labeled by the content_type of their very first view that day (earliest viewed_at, breaking ties by smallest view_id). Related device-group, peak-hour, and missing-content summaries are covered in the explanation's follow-up section.

    Across all agent-days on each event_date, we return the count (agent_days) and fraction (share, rounded to 4 decimals) for each first-seen content_type:

    Example 1 expected output:
    +------------+--------------+------------+--------+
    | event_date | content_type | agent_days | share  |
    +------------+--------------+------------+--------+
    | 2024-05-10 | article      | 2          | 0.6667 |
    | 2024-05-10 | video        | 1          | 0.3333 |
    | 2024-05-11 | podcast      | 1          | 0.5    |
    | 2024-05-11 | video        | 1          | 0.5    |
    +------------+--------------+------------+--------+
    
  2. Extract the UTC calendar date

    Every viewed_at value is already in UTC and formatted as 'YYYY-MM-DD HH:MM:SS'. We need the calendar date in two places: to separate a viewer's activity on May 10 from May 11, and to label the output column event_date.

    • In SQLite, DATE(viewed_at) extracts '2024-05-10' from '2024-05-10 07:20:00'. (In PostgreSQL or Snowflake, you write CAST(viewed_at AS DATE) or viewed_at::date.)
    • Because ISO-8601 strings (YYYY-MM-DD HH:MM:SS) put year, month, day, hour, minute, and second from biggest unit to smallest, ORDER BY viewed_at ASC sorts timestamps in true chronological order.
    DATE(viewed_at) AS event_date
    
  3. Pick the first view of each agent-day with ROW_NUMBER

    To isolate the earliest view per (agent_id, event_date), we use a CTE (Common Table Expression — a named temporary step written with WITH) and the ROW_NUMBER() window function (which numbers rows inside each PARTITION BY group without collapsing them).

    Look carefully at the sort order and at why simpler shortcuts fail:

    Trap 1 - Why viewed_at MUST come before view_id (Example 1, agent v2 on 2024-05-11):
      view_id = 17 | viewed_at = 2024-05-11 13:30:00 | article  (smaller ID, but LATER time!)
      view_id = 18 | viewed_at = 2024-05-11 09:15:00 | video    (earlier time -> rn = 1!)
    
    Trap 2 - Why ROW_NUMBER() beats MIN(viewed_at) or RANK() on exact timestamp ties (v1 on 2024-05-11):
      view_id = 16 | viewed_at = 2024-05-11 08:00:00 | article  -> rn = 2
      view_id = 15 | viewed_at = 2024-05-11 08:00:00 | podcast  -> rn = 1 (smaller view_id wins)
      -> Joining on MIN(viewed_at) or filtering RANK() = 1 would keep BOTH rows and double-count v1!
    

    Filtering WHERE rn = 1 guarantees at most one row per (agent_id, event_date):

    WITH ranked_views AS (
        -- Number each viewer's page views within each UTC calendar date from earliest to latest;
        -- break exact timestamp ties using the smaller view_id.
        SELECT
            agent_id,
            DATE(viewed_at) AS event_date,
            content_type,
            ROW_NUMBER() OVER (
                PARTITION BY agent_id, DATE(viewed_at)
                ORDER BY viewed_at ASC, view_id ASC
            ) AS rn
        FROM page_views
    ),
    first_views AS (
        -- Keep one row per (agent_id, event_date): that agent-day's very first content_type.
        SELECT event_date, content_type
        FROM ranked_views
        WHERE rn = 1
    )
    
  4. Count agent-days and compute daily shares in one pass

    Now first_views has one row per agent-day. Grouping first_views by (event_date, content_type) gives each content type's COUNT(*) AS agent_days.

    How do we divide each row's agent_days by the total agent-days on that same date without scanning first_views a second time? In SQL's execution order, GROUP BY runs before SELECT window functions. That means SUM(COUNT(*)) OVER (PARTITION BY event_date) takes the already-computed COUNT(*) of each (event_date, content_type) group and sums those counts across all content types sharing the same event_date:

    After GROUP BY event_date, content_type:      Window SUM(COUNT(*)) OVER (PARTITION BY event_date):
      2024-05-10 | article | COUNT(*) = 2    --->   2 + 1 = 3  -> share = 1.0 * 2 / 3 = 0.6667
      2024-05-10 | video   | COUNT(*) = 1    --->   2 + 1 = 3  -> share = 1.0 * 1 / 3 = 0.3333
      2024-05-11 | podcast | COUNT(*) = 1    --->   1 + 1 = 2  -> share = 1.0 * 1 / 2 = 0.5
      2024-05-11 | video   | COUNT(*) = 1    --->   1 + 1 = 2  -> share = 1.0 * 1 / 2 = 0.5
    

    Two subtle details prevent bugs here: - Use COUNT(*), not COUNT(content_type). If a viewer's first view has content_type IS NULL, GROUP BY creates a NULL group; COUNT(*) counts those agent-days properly, whereas COUNT(content_type) would return 0! - Multiply by 1.0 before / so SQLite performs floating-point division instead of truncating 2 / 3 to integer 0.

    SELECT
        event_date,
        content_type,
        COUNT(*) AS agent_days,
        ROUND(
            1.0 * COUNT(*) / SUM(COUNT(*)) OVER (PARTITION BY event_date),
            4
        ) AS share
    FROM first_views
    GROUP BY event_date, content_type
    
  5. Trace Example 1 from raw logs to shares

    Step 1 - Rank views inside each (agent_id, event_date):
      event_date | agent_id | raw views (time, #view_id, type)               | rn = 1 winner
      -----------+----------+------------------------------------------------+--------------
      2024-05-10 | v1       | (07:20, #10, article), (11:45, #11, video)     | article
      2024-05-10 | v2       | (06:50, #12, article), (19:10, #13, podcast)   | article
      2024-05-10 | v3       | (14:00, #14, video)                            | video
      2024-05-11 | v1       | (08:00, #15, podcast), (08:00, #16, article)   | podcast (#15 < #16)
      2024-05-11 | v2       | (09:15, #18, video),   (13:30, #17, article)   | video (#18 is earlier!)
    
    Step 2 - Aggregate first_views by (event_date, content_type):
      - 2024-05-10 (total = 3 agent-days):
          article: 2 -> ROUND(1.0 * 2 / 3, 4) = 0.6667
          video:   1 -> ROUND(1.0 * 1 / 3, 4) = 0.3333
      - 2024-05-11 (total = 2 agent-days):
          podcast: 1 -> ROUND(1.0 * 1 / 2, 4) = 0.5
          video:   1 -> ROUND(1.0 * 1 / 2, 4) = 0.5
    
  6. Put the complete query together

    WITH ranked_views AS (
        -- Number each viewer's page views within each UTC calendar date from earliest to latest;
        -- break exact timestamp ties using the smaller view_id.
        SELECT
            agent_id,
            DATE(viewed_at) AS event_date,
            content_type,
            ROW_NUMBER() OVER (
                PARTITION BY agent_id, DATE(viewed_at)
                ORDER BY viewed_at ASC, view_id ASC
            ) AS rn
        FROM page_views
    ),
    first_views AS (
        -- Keep one row per (agent_id, event_date): that agent-day's very first content_type.
        SELECT event_date, content_type
        FROM ranked_views
        WHERE rn = 1
    )
    -- Count(*) (not COUNT(content_type)) keeps NULL content_type groups in both the numerator
    -- and the date's window-sum denominator; 1.0 * avoids SQLite integer division.
    SELECT
        event_date,
        content_type,
        COUNT(*) AS agent_days,
        ROUND(
            1.0 * COUNT(*) / SUM(COUNT(*)) OVER (PARTITION BY event_date),
            4
        ) AS share
    FROM first_views
    GROUP BY event_date, content_type
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine standing at the front entrance of a digital publisher (with articles, videos, and podcasts) and asking: "Each day when a reader visits us for the very first time, what kind of content brought them through the door?" Even if reader v1 opens an article at 7:20 AM and then watches videos later that morning, v1 gets just one entry ticket on that date — called an agent-day (one unique agent_id active on one calendar date) — stamped article. Once you collect one entry ticket per reader per day, you count each day's tickets by content_type and divide by the total tickets handed out on that date.

A naive query that skips the per-reader step and groups page_views directly by (DATE(viewed_at), content_type) measures the share of all page views rather than first views, letting heavy multi-page sessions swamp casual readers. Trying to grab first views by finding MIN(viewed_at) per (agent_id, event_date) and joining back to page_views also breaks whenever two events land in the exact same second, because both match the minimum timestamp and count that agent-day twice. Ordering by view_id alone fails too, because delayed mobile or tablet batches can assign a larger view_id to an earlier viewed_at timestamp.

Walking through Example 1 shows how ranking with ROW_NUMBER() and aggregating with a window sum solves the problem cleanly: 1. Number each viewer's daily views (ranked_views): A window function (a SQL function with OVER (...) that computes a rank or running value across related rows without collapsing them) partitions by (agent_id, DATE(viewed_at)) and orders by (viewed_at ASC, view_id ASC). 2. Keep rn = 1 (first_views): On 2024-05-10, v1 starts with article (07:20), v2 starts with article (06:50), and v3 starts with video (14:00). On 2024-05-11, v1 starts with podcast (view_id = 15 breaks the 08:00:00 tie with view_id = 16), and v2 starts with video (view_id = 18 at 09:15, beating view_id = 17 at 13:30!). 3. Count and divide per date: On 2024-05-10, article gets 2 of 3 agent-days (share = 0.6667) and video gets 1 of 3 (share = 0.3333). On 2024-05-11, podcast and video each get 1 of 2 agent-days (share = 0.5).

Complexity

Let N be the total number of rows in page_views and A the number of distinct (agent_id, event_date) agent-days (A <= N).

  • Time: O(N log N). Computing ROW_NUMBER() OVER (PARTITION BY agent_id, DATE(viewed_at) ORDER BY viewed_at, view_id) sorts the N event rows in O(N log N) time. Filtering rn = 1 scans N rows in O(N) time, and grouping the resulting A agent-days by (event_date, content_type) plus summing across each date's handful of content types takes O(A log A) (or O(A) with hash aggregation).
  • Space: O(N). Sorting the N input rows for the window function uses O(N) memory (or spills to disk on very large logs), while first_views holds O(A) rows.

In production, event tables hold billions of rows and are partitioned on disk by event_date (or viewed_at date). Adding a half-open timestamp range filter (such as viewed_at >= '2024-05-10 00:00:00' AND viewed_at < '2024-05-17 00:00:00') lets the engine skip older partitions completely, and storing an index or clustering key on (event_date, agent_id, viewed_at, view_id) lets the database stream each agent-day's rows in sort order without a full sort.

Edge cases

  • Exact timestamp ties: If an agent logs two views at '2024-05-11 08:00:00', ORDER BY viewed_at ASC, view_id ASC deterministically picks the smaller view_id, and ROW_NUMBER() ensures only one row gets rn = 1.
  • Out-of-order view_id vs. viewed_at: viewed_at is the primary sort key, so an earlier viewed_at with a larger view_id (like view 18 vs. view 17 in Example 1) still wins.
  • Midnight boundary (23:59:59 vs. 00:00:00): DATE(viewed_at) splits views just before and at/after UTC midnight into separate agent-days.
  • NULL content_type on a first view: GROUP BY event_date, content_type places NULL in its own group, and COUNT(*) counts it in both agent_days and the date's SUM(COUNT(*)) denominator so shares still sum to 1.0.
  • NULL content_id: A section or front-page visit with content_id IS NULL (like view 12 in Example 1) is still a valid page view with a content_type.
  • Empty page_views table: Returns zero rows without division-by-zero errors.

Common mistakes

  • Ordering by view_id instead of (viewed_at, view_id): Fails whenever events arrive out of chronological order (misclassifying v2 on 2024-05-11 in Example 1).
  • Using RANK() or MIN(viewed_at) instead of ROW_NUMBER(): Keeps multiple rows when two views tie at the earliest timestamp, inflating agent_days.
  • Using SUM(COUNT(*)) OVER () without PARTITION BY event_date: Divides by the grand total across all dates instead of each date's own total.
  • Writing COUNT(content_type) instead of COUNT(*): Returns 0 for any group where content_type IS NULL, breaking both agent_days and share.
  • Omitting 1.0 * in SQLite: Integer division truncates 2 / 3 and 1 / 2 to 0.
  • Grouping by raw viewed_at instead of DATE(viewed_at): Treats every timestamp down to the second as a separate group instead of rolling up by calendar day.

Alternative approaches

  • Separate daily_totals CTE instead of nested SUM(COUNT(*)) OVER (...): If your team prefers explicit CTEs over combining GROUP BY and window functions in the same SELECT, first group first_views into type_counts(event_date, content_type, agent_days), compute daily_totals(event_date, total_agent_days) from type_counts, and join the two on event_date. Both plans perform the exact same work and produce identical rows.

Follow-up questions

  • Grouping 'phone' and 'tab' as 'mobile' versus 'desktop', how do you compute distinct non-NULL content_ids and total views per group, and when could those two counts ever match? Map device_type IN ('phone', 'tab') to 'mobile' and 'desktop' to 'desktop' using CASE, then aggregate with COUNT(DISTINCT content_id) (which automatically ignores NULLs in SQL) and COUNT(*). On Example 1, mobile has 3 distinct non-NULL items (art_9, pod_2, vid_7) across 6 total views, and desktop has 2 distinct items (vid_4, art_5) across 3 total views. In general, the two counts do not match (unique_contents_viewed <= total_views) because popular items are viewed repeatedly and landing pages have content_id IS NULL; they are equal only when every single view in that device group has a non-NULL, never-repeated content_id:

sql SELECT CASE WHEN device_type IN ('phone', 'tab') THEN 'mobile' WHEN device_type = 'desktop' THEN 'desktop' END AS device_group, COUNT(DISTINCT content_id) AS unique_contents_viewed, COUNT(*) AS total_views FROM page_views WHERE device_type IN ('phone', 'tab', 'desktop') GROUP BY CASE WHEN device_type IN ('phone', 'tab') THEN 'mobile' WHEN device_type = 'desktop' THEN 'desktop' END;

  • How would you write a query to return the top 3 busiest UTC hours (0–23) for each device_type, breaking ties toward earlier hours? Extract the integer hour (CAST(strftime('%H', viewed_at) AS INTEGER) in SQLite, or EXTRACT(HOUR FROM viewed_at) in PostgreSQL/BigQuery/Snowflake), count views per (device_type, hour_of_day), and rank hours inside each device_type with ROW_NUMBER() OVER (PARTITION BY device_type ORDER BY views DESC, hour_of_day ASC). Filtering rn <= 3 returns up to 3 hours per device and breaks ties toward smaller hours (on Example 1: phone returns hour 8 with 2 views followed by hours 7 and 19 with 1 view each; desktop returns hours 11, 13, 14 with 1 view each; tab returns hours 6, 9 with 1 view each):

sql WITH hourly_views AS ( SELECT device_type, CAST(strftime('%H', viewed_at) AS INTEGER) AS hour_of_day, COUNT(*) AS views FROM page_views GROUP BY device_type, CAST(strftime('%H', viewed_at) AS INTEGER) ), ranked_hours AS ( SELECT device_type, hour_of_day, views, ROW_NUMBER() OVER ( PARTITION BY device_type ORDER BY views DESC, hour_of_day ASC ) AS rn FROM hourly_views ) SELECT device_type, hour_of_day, views FROM ranked_hours WHERE rn <= 3 ORDER BY device_type ASC, rn ASC;

  • How can you compute total distinct non-NULL content_ids alongside the count of NULL-content events in a single table scan, even if page_views is empty? COUNT(DISTINCT content_id) counts distinct non-NULL content IDs, while COUNT(*) - COUNT(content_id) counts rows where content_id IS NULL because COUNT(*) counts every row and COUNT(content_id) counts only non-NULL content_id rows (and unlike SUM(CASE WHEN ...), COUNT(*) - COUNT(content_id) returns 0 rather than NULL on an empty table!). On Example 1, this returns unique_contents_viewed = 5 and null_content_events = 1 (view 12):

sql SELECT COUNT(DISTINCT content_id) AS unique_contents_viewed, COUNT(*) - COUNT(content_id) AS null_content_events FROM page_views;

Follow-up questions

Similar questions

More The New York Times interview questions

All 1 The New York Times questions →