SQL
Lab
Spotify Spotify Interview Question 05

Premium
vs Free
Users

Calculate average listening time for premium vs free users.

Table Schema

Inspect
Table

interactive
ColumnType
user_idinteger
subscription_typevarchar
ColumnType
user_idinteger
duration_secondsinteger

Sample Data

Input
Output

Sample Input: users
user_idsubscription_type
101Premium
102Free
103Premium
104Free
Sample Input: streams
user_idduration_seconds
101200
101300
102100
103400
104150
103200
Expected Output
subscription_typeavg_time
Free125.00
Premium550.00

SQL Editor

Run
Query

postgresql
Waiting for query

subscription_typeavg_time
Free125.00
Premium550.00

Hints

Unlock
Clues

Hint 01: Identify the grouping level required by the output.
Hint 02: Aggregate with COUNT, SUM, AVG, or a window function as needed.
Hint 03: Filter after aggregation with HAVING or after ranking with an outer query.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH user_time AS (
  SELECT user_id, SUM(duration_seconds) AS total_time
  FROM streams
  GROUP BY user_id
)
SELECT u.subscription_type, ROUND(AVG(ut.total_time), 2) AS avg_time
FROM users u
JOIN user_time ut ON u.user_id = ut.user_id
GROUP BY u.subscription_type;

Explanation

Step By
Step

01

Read the expected output columns to determine the final grain.

02

Aggregate or rank the input rows to calculate the requested metric.

03

Filter, sort, and alias the final columns to match the output.

Related Questions

Keep
Solving