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 fromviewed_at.content_type: thecontent_typeof the viewer's first page view onevent_date.agent_days: how many distinct viewers onevent_datehad thatcontent_typeon their first view of the day.share:agent_daysdivided by the totalagent_daysacross all content types onevent_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_attimestamps in UTC; midnight00:00:00begins a newevent_date. - A row with
content_id IS NULLstill participates in first-view selection. - If a viewer's winning first view has
content_type IS NULL, reportNULLas its owncontent_typegroup and include those agent-days in the date'ssharedenominator. - Round
shareto 4 decimal places using floating-point division; output rows may appear in any order.
Step-by-step walkthrough
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 viewerv1loads 50 pages on2024-05-10,v1contributes one agent-day on2024-05-10, labeled by thecontent_typeof their very first view that day (earliestviewed_at, breaking ties by smallestview_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-seencontent_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 | +------------+--------------+------------+--------+Extract the UTC calendar date
Every
viewed_atvalue 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 columnevent_date.- In SQLite,
DATE(viewed_at)extracts'2024-05-10'from'2024-05-10 07:20:00'. (In PostgreSQL or Snowflake, you writeCAST(viewed_at AS DATE)orviewed_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 ASCsorts timestamps in true chronological order.
DATE(viewed_at) AS event_date- In SQLite,
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 withWITH) and theROW_NUMBER()window function (which numbers rows inside eachPARTITION BYgroup 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 = 1guarantees 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 )Count agent-days and compute daily shares in one pass
Now
first_viewshas one row per agent-day. Groupingfirst_viewsby(event_date, content_type)gives each content type'sCOUNT(*) AS agent_days.How do we divide each row's
agent_daysby the total agent-days on that same date without scanningfirst_viewsa second time? In SQL's execution order,GROUP BYruns beforeSELECTwindow functions. That meansSUM(COUNT(*)) OVER (PARTITION BY event_date)takes the already-computedCOUNT(*)of each(event_date, content_type)group and sums those counts across all content types sharing the sameevent_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.5Two subtle details prevent bugs here: - Use
COUNT(*), notCOUNT(content_type). If a viewer's first view hascontent_type IS NULL,GROUP BYcreates aNULLgroup;COUNT(*)counts those agent-days properly, whereasCOUNT(content_type)would return0! - Multiply by1.0before/so SQLite performs floating-point division instead of truncating2 / 3to integer0.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_typeTrace 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.5Put 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). ComputingROW_NUMBER() OVER (PARTITION BY agent_id, DATE(viewed_at) ORDER BY viewed_at, view_id)sorts theNevent rows inO(N log N)time. Filteringrn = 1scansNrows inO(N)time, and grouping the resultingAagent-days by(event_date, content_type)plus summing across each date's handful of content types takesO(A log A)(orO(A)with hash aggregation). - Space:
O(N). Sorting theNinput rows for the window function usesO(N)memory (or spills to disk on very large logs), whilefirst_viewsholdsO(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 ASCdeterministically picks the smallerview_id, andROW_NUMBER()ensures only one row getsrn = 1. - Out-of-order
view_idvs.viewed_at:viewed_atis the primary sort key, so an earlierviewed_atwith a largerview_id(like view18vs. view17in Example 1) still wins. - Midnight boundary (
23:59:59vs.00:00:00):DATE(viewed_at)splits views just before and at/after UTC midnight into separate agent-days. NULLcontent_typeon a first view:GROUP BY event_date, content_typeplacesNULLin its own group, andCOUNT(*)counts it in bothagent_daysand the date'sSUM(COUNT(*))denominator so shares still sum to1.0.NULLcontent_id: A section or front-page visit withcontent_id IS NULL(like view12in Example 1) is still a valid page view with acontent_type.- Empty
page_viewstable: Returns zero rows without division-by-zero errors.
Common mistakes
- Ordering by
view_idinstead of(viewed_at, view_id): Fails whenever events arrive out of chronological order (misclassifyingv2on2024-05-11in Example 1). - Using
RANK()orMIN(viewed_at)instead ofROW_NUMBER(): Keeps multiple rows when two views tie at the earliest timestamp, inflatingagent_days. - Using
SUM(COUNT(*)) OVER ()withoutPARTITION BY event_date: Divides by the grand total across all dates instead of each date's own total. - Writing
COUNT(content_type)instead ofCOUNT(*): Returns0for any group wherecontent_type IS NULL, breaking bothagent_daysandshare. - Omitting
1.0 *in SQLite: Integer division truncates2 / 3and1 / 2to0. - Grouping by raw
viewed_atinstead ofDATE(viewed_at): Treats every timestamp down to the second as a separate group instead of rolling up by calendar day.
Alternative approaches
- Separate
daily_totalsCTE instead of nestedSUM(COUNT(*)) OVER (...): If your team prefers explicit CTEs over combiningGROUP BYand window functions in the sameSELECT, first groupfirst_viewsintotype_counts(event_date, content_type, agent_days), computedaily_totals(event_date, total_agent_days)fromtype_counts, and join the two onevent_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'usingCASE, then aggregate withCOUNT(DISTINCT content_id)(which automatically ignoresNULLs in SQL) andCOUNT(*). On Example 1,mobilehas3distinct non-NULLitems (art_9,pod_2,vid_7) across6total views, anddesktophas2distinct items (vid_4,art_5) across3total views. In general, the two counts do not match (unique_contents_viewed <= total_views) because popular items are viewed repeatedly and landing pages havecontent_id IS NULL; they are equal only when every single view in that device group has a non-NULL, never-repeatedcontent_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, orEXTRACT(HOUR FROM viewed_at)in PostgreSQL/BigQuery/Snowflake), count views per(device_type, hour_of_day), and rank hours inside eachdevice_typewithROW_NUMBER() OVER (PARTITION BY device_type ORDER BY views DESC, hour_of_day ASC). Filteringrn <= 3returns up to 3 hours per device and breaks ties toward smaller hours (on Example 1:phonereturns hour8with2views followed by hours7and19with1view each;desktopreturns hours11, 13, 14with1view each;tabreturns hours6, 9with1view 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-NULLcontent IDs, whileCOUNT(*) - COUNT(content_id)counts rows wherecontent_id IS NULLbecauseCOUNT(*)counts every row andCOUNT(content_id)counts only non-NULLcontent_idrows (and unlikeSUM(CASE WHEN ...),COUNT(*) - COUNT(content_id)returns0rather thanNULLon an empty table!). On Example 1, this returnsunique_contents_viewed = 5andnull_content_events = 1(view12):
sql
SELECT
COUNT(DISTINCT content_id) AS unique_contents_viewed,
COUNT(*) - COUNT(content_id) AS null_content_events
FROM page_views;
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?
- 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?
- 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?
Similar questions
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression
- Week-over-Week Net Order Revenue Change