Table Schema
Inspect
Table
| Column | Type |
|---|---|
| user_id | integer |
| login_date | date |
Find users who logged in for 3 consecutive days.
Table Schema
| Column | Type |
|---|---|
| user_id | integer |
| login_date | date |
Sample Data
| user_id | login_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, login_date
FROM logins
),
streaks AS (
SELECT
user_id,
login_date - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date)::int AS streak_group
FROM distinct_days
)
SELECT user_id
FROM streaks
GROUP BY user_id, streak_group
HAVING COUNT(*) >= 3;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