Active Subscriptions for a Video Streaming Platform
Beginner Mode

Scenario

You work for a video streaming company and have two tables: one recording daily watch activity and another tracking subscription periods for each user.

Task

Write a Snowflake SQL query that:

  1. Handles NULL values in the end_date column of {{ ref("subscriptions") }} (NULL means the subscription is still active) by replacing them with a far-future date
  2. Joins {{ ref("watch_history") }} with the normalized subscriptions on user_id, keeping only rows where watch_date falls between start_date and the normalized end_date (inclusive)
  3. Groups by user_id and sums watch_duration as total_watch_time
  4. Returns user_id and total_watch_time

Schema

watch_history

Column Type Description
user_id String Unique identifier for the user
watch_duration Integer Minutes watched on that date
watch_date String Date content was watched (YYYY-MM-DD)

subscriptions

Column Type Description
user_id String Unique identifier for the user
start_date String Subscription start date (YYYY-MM-DD)
end_date Date Subscription end date, or NULL if still active

Example

watch_history:

user_id watch_duration watch_date
A1 30 2024-06-01
A1 55 2024-06-05
A2 40 2024-06-03
A2 25 2024-06-10
A3 60 2024-06-15

subscriptions:

user_id start_date end_date
A1 2024-06-01 2024-06-07
A2 2024-06-01 NULL
A3 2024-06-10 2024-06-20

Expected Output:

user_id total_watch_time
A1 85
A2 65
A3 60

Note: A1 watched 30 + 55 = 85 minutes, both dates within Jun 1 to Jun 7. A2's subscription has no end date (still active), so all watch dates qualify (40 + 25 = 65). A3 watched on Jun 15, which falls within Jun 10 to Jun 20 (60 minutes).

Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →