cswork / libraryOpen practice workspace

Coding questions · Amazon

Calculate Weekly, Monthly Hours Watched by Premium Users

This question evaluates a candidate's ability to perform time-based aggregation and data manipulation in SQL and Python, including grouping, filtering by subscription status, and converting minute-level metrics into hours.

watch_events

+-----------+----------+----------------+-----------------------+----------------+
| user_id   | video_id | watched_minutes| watched_at            | subscription   |
+-----------+----------+----------------+-----------------------+----------------+
| 101       | v89      | 30             | 2023-04-03 10:22:05   | premium        |
| 102       | v12      | 12             | 2023-04-04 08:10:00   | free           |
| 101       | v77      | 55             | 2023-04-09 14:18:20   | premium        |
| 103       | v51      | 20             | 2023-04-11 20:00:00   | premium        |
| 102       | v23      | 42             | 2023-05-01 09:00:12   | free           |
+-----------+----------+----------------+-----------------------+----------------+
Scenario

Streaming platform wants weekly and monthly total video hours watched by premium users to monitor engagement trends.

Question

Given the watch_events table, write SQL that returns for each user_id the total watched_minutes converted to hours aggregated by week and by month, filtered where subscription = 'premium'.

Hints

Use DATE_TRUNC or EXTRACT for week/month, SUM(watched_minutes)/60 AS watched_hours, and GROUP BY.

Weekly and Monthly Watched Hours by Premium Users

For premium streaming users, aggregate watched minutes into weekly and monthly watched hours.

Use watch_events and include only rows where subscription = 'premium'. Return one row per (user_id, period_type, period_start) with these columns:

  • user_id
  • period_type: either week or month
  • period_start: the DATE_TRUNC start of that week or month, formatted as YYYY-MM-DD HH24:MI:SS
  • watched_hours: total watched minutes divided by 60, rounded to 2 decimals

Order by user_id, then period_start, then period_type.

Table watch_events

columntypeconstraints
user_idINTEGER
video_idVARCHAR
watched_minutesINTEGER
watched_atTIMESTAMP
subscriptionVARCHAR

Sample data:

subscriptionuser_idvideo_idwatched_atwatched_minutes
premium101v892023-04-03 10:22:0530
free102v122023-04-04 08:10:0012
premium101v772023-04-09 14:18:2055
premium103v512023-04-11 20:00:0020
free102v232023-05-01 09:00:1242

Expected output

Weekly and monthly watched hours for premium users, with formatted period starts.

period_startperiod_typeuser_idwatched_hours
2023-04-01 00:00:00month1011.42
2023-04-03 00:00:00week1011.42
2023-04-01 00:00:00month1030.33
2023-04-10 00:00:00week1030.33

Hints

  1. Filter to premium subscriptions before aggregating.
  2. Use DATE_TRUNC for week and month buckets.
  3. UNION ALL the weekly and monthly aggregates.