Table Schema
Inspect
Table
| Column | Type |
|---|---|
| user_id | integer |
| subscription_type | varchar |
| Column | Type |
|---|---|
| user_id | integer |
| duration_seconds | integer |
Calculate average listening time for premium vs free users.
Table Schema
| Column | Type |
|---|---|
| user_id | integer |
| subscription_type | varchar |
| Column | Type |
|---|---|
| user_id | integer |
| duration_seconds | integer |
Sample Data
| user_id | subscription_type |
|---|---|
| 101 | Premium |
| 102 | Free |
| 103 | Premium |
| 104 | Free |
| user_id | duration_seconds |
|---|---|
| 101 | 200 |
| 101 | 300 |
| 102 | 100 |
| 103 | 400 |
| 104 | 150 |
| 103 | 200 |
| subscription_type | avg_time |
|---|---|
| Free | 125.00 |
| Premium | 550.00 |
SQL Editor
| subscription_type | avg_time |
|---|---|
| Free | 125.00 |
| Premium | 550.00 |
Hints
Solution
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
Read the expected output columns to determine the final grain.
Aggregate or rank the input rows to calculate the requested metric.
Filter, sort, and alias the final columns to match the output.
Related Questions