Table Schema
Inspect
Table
| Column | Type |
|---|---|
| user_id | integer |
| subscription_month | date |
Find users who remained subscribed for at least 2 consecutive months.
Table Schema
| Column | Type |
|---|---|
| user_id | integer |
| subscription_month | date |
Sample Data
| user_id | subscription_month |
|---|---|
| 101 | 2024-01-01 |
| 101 | 2024-02-01 |
| 102 | 2024-01-01 |
| 103 | 2024-02-01 |
| 104 | 2024-01-01 |
| 104 | 2024-02-01 |
| user_id |
|---|
| 101 |
| 104 |
SQL Editor
| user_id |
|---|
| 101 |
| 104 |
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 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
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