Practice 3: Login Streaks of 3 Days or More
The service team asks: "Which users logged in three or more days in a row, and over which days?"
Data
The login log logins(user_id, day_no) is a CTE built with VALUES. day_no numbers the days from the service's first day as 1. A user who logs in several times a day leaves several rows for that day.
Requirements
- For each user, find the ranges where the day number goes up by 1 without a break.
- Return only ranges of 3 days or more.
- Several logins on one day count as one day.
Result format
| Column | Meaning |
|---|---|
user_id | User |
start_day | First day of the range |
end_day | Last day of the range |
streak_days | Number of days in the range |
Sort by user_id, then start_day.
My solution
Keep the logins CTE as it is and change the SELECT below it.
My solution
WITH logins (user_id, day_no) AS (
SELECT * FROM (VALUES
(1, 1), (1, 2), (1, 2), (1, 3), (1, 5), (1, 6), (1, 7), (1, 8), (1, 10),
(2, 1), (2, 3), (2, 4), (2, 5), (2, 9), (2, 10),
(3, 2), (3, 3), (3, 10), (3, 11), (3, 12), (3, 12), (3, 13), (3, 14),
(4, 4), (4, 6), (4, 8), (4, 9)
) AS t (user_id, day_no)
)
SELECT user_id, day_no
FROM logins
ORDER BY user_id, day_no
Hints
- Gaps and islands: subtracting
ROW_NUMBER()from consecutive values gives the same value within an island. To count per user, usePARTITION BY user_id. - When a day appears twice, the row number goes up but the day does not, and the island splits. Remove the duplicates first (
DISTINCT), or pick a function that gives duplicates the same number. - The day-count condition filters after grouping, so it goes in
HAVING(GROUP BY).