Table Schema
Inspect
Table
| Column | Type |
|---|---|
| user_id | integer |
| open_date | date |
Find users who opened the app on 3 consecutive days.
Table Schema
| Column | Type |
|---|---|
| user_id | integer |
| open_date | date |
Sample Data
| user_id | open_date |
|---|---|
| 101 | 2024-01-01 |
| 101 | 2024-01-02 |
| 101 | 2024-01-03 |
| 102 | 2024-01-01 |
| 102 | 2024-01-03 |
| 103 | 2024-01-05 |
| 104 | 2024-01-06 |
| user_id |
|---|
| 101 |
SQL Editor
| user_id |
|---|
| 101 |
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 distinct_days AS (
SELECT DISTINCT user_id, open_date
FROM app_usage
),
streaks AS (
SELECT
user_id,
open_date - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY open_date)::int AS streak_group
FROM distinct_days
)
SELECT user_id
FROM streaks
GROUP BY user_id, streak_group
HAVING COUNT(*) >= 3;Explanation
Deduplicate user-date pairs.
Build consecutive date groups using ROW_NUMBER.
Keep users with a group of at least 3 days.
Related Questions