Table Schema
Inspect
Table
| Column | Type |
|---|---|
| host_id | integer |
| booking_date | date |
Find hosts who had bookings in 3 consecutive months.
Table Schema
| Column | Type |
|---|---|
| host_id | integer |
| booking_date | date |
Sample Data
| host_id | booking_date |
|---|---|
| 201 | 2024-01-01 |
| 201 | 2024-02-01 |
| 201 | 2024-03-01 |
| 202 | 2024-01-01 |
| 202 | 2024-03-01 |
| 203 | 2024-02-01 |
| host_id |
|---|
| 201 |
SQL Editor
| host_id |
|---|
| 201 |
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 host_id, DATE_TRUNC('month', booking_date) AS month
FROM bookings
),
streaks AS (
SELECT
host_id,
month - (ROW_NUMBER() OVER (PARTITION BY host_id ORDER BY month) * INTERVAL '1 month') AS streak_group
FROM months
)
SELECT host_id
FROM streaks
GROUP BY host_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