SQL
Lab
Spotify Spotify Interview Question 09

Subscription
Retention

Find users who remained subscribed for at least 2 consecutive months.

Table Schema

Inspect
Table

interactive
ColumnType
user_idinteger
subscription_monthdate

Sample Data

Input
Output

Sample Input: subscriptions
user_idsubscription_month
1012024-01-01
1012024-02-01
1022024-01-01
1032024-02-01
1042024-01-01
1042024-02-01
Expected Output
user_id
101
104

SQL Editor

Run
Query

postgresql
Waiting for query

user_id
101
104

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 months AS (
  SELECT DISTINCT user_id, DATE_TRUNC('month', subscription_month) AS month
  FROM subscriptions
),
streaks AS (
  SELECT
    user_id,
    month - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY month) * INTERVAL '1 month') AS streak_group
  FROM months
)
SELECT user_id
FROM streaks
GROUP BY user_id, streak_group
HAVING COUNT(*) >= 2;

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