Find each customer’s longest active-day streak
Your task
Return customer_id and longest_streak for every customer with at least one event. Count consecutive calendar days with any activity, counting each day once. Sort by customer ID.
Consecutive days form a streak. Subtracting the row number from each distinct date gives a common key within a streak.
Sample data
product_events| id | customer_id | session_key | event_at | event_name |
|---|---|---|---|---|
| 301 | 1 | a-1 | 2025-01-02 09:00:00 | search |
| 302 | 1 | a-1 | 2025-01-02 09:01:00 | view_product |
| 303 | 1 | a-1 | 2025-01-02 09:02:00 | add_to_cart |
| 304 | 1 | a-1 | 2025-01-02 09:04:00 | purchase |
| 305 | 2 | c-1 | 2025-01-05 10:00:00 | view_product |
| 306 | 2 | c-1 | 2025-01-05 10:01:00 | purchase |
| 307 | 2 | c-1 | 2025-01-05 10:02:00 | add_to_cart |
| 308 | 3 | j-1 | 2025-01-12 11:00:00 | search |
| 309 | 3 | j-1 | 2025-01-12 11:02:00 | view_product |
| 310 | 4 | m-1 | 2025-02-01 08:00:00 | view_product |
Preview of 10 of 25 rows
Expected output
| customer_id | longest_streak |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 2 |
Show a hint
Deduplicate dates per customer, number them, then group by JULIANDAY(active_date) minus the row number.
Product events and funnels guide
Choose the event, session, or customer grain
An event is one logged action. A session is a group of events with the same session_key. A customer can have several sessions. Choose the grain before counting so a busy visitor cannot accidentally count as many people.
SELECT event_name, COUNT(*) AS events, COUNT(DISTINCT session_key) AS sessions
FROM product_events
GROUP BY event_name
ORDER BY event_name;Order events before evaluating a funnel
A funnel measures steps completed in a defined order. Events in the same session can share an exact timestamp, so use the event ID as a tie-breaker. A session with a purchase before the cart event does not meet a view, cart, purchase funnel.
SELECT session_key, event_name,
ROW_NUMBER() OVER (PARTITION BY session_key ORDER BY event_at, id) AS position
FROM product_events
ORDER BY session_key, position;Worked solution
WITH active AS (SELECT DISTINCT customer_id,DATE(event_at) AS day FROM product_events), numbered AS (SELECT customer_id,JULIANDAY(day)-ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY day) AS streak FROM active), lengths AS (SELECT customer_id,COUNT(*) AS days FROM numbered GROUP BY customer_id,streak) SELECT customer_id,MAX(days) AS longest_streak FROM lengths GROUP BY customer_id ORDER BY customer_id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
