Sessionize the events table. Order each user's events by event_time, breaking ties by event_id. A new session starts when the gap between two consecutive events of the same user is more than 1800 seconds (30 minutes). Return user_id, event_id, event_time and session_id for every event.
session_id has the form <user_id>-<n>, for example 5-1 or 5-2. n starts at 1 for each user and goes up by 1 with each new session. A gap of exactly 1800 seconds stays in the same session.
Input Table(s)
events
| Column | Type | Meaning |
|---|
| event_id | INT | Event id |
| user_id | INT | User who produced the event, never NULL |
| event_time | TIMESTAMP | When the event happened, never NULL |
Primary key: event_id.
Output Contract
One row per event, with these columns in this order:
| Column | Meaning |
|---|
| user_id | The event's user |
| event_id | The event's id |
| event_time | The event's timestamp |
| session_id | Text of the form <user_id>-<n>, where n is the user's session number starting at 1 |
Order the rows by user_id ascending, then event_time ascending, then event_id ascending.
Example
events
| event_id | user_id | event_time |
|---|
| 10 | 1 | 2024-02-01 08:00:00 |
| 11 | 1 | 2024-02-01 08:30:00 |
| 12 | 2 | 2024-02-01 08:05:00 |
| 13 | 2 | 2024-02-01 09:00:00 |
Expected result:
| user_id | event_id | event_time | session_id |
|---|
| 1 | 10 | 2024-02-01 08:00:00 | 1-1 |
| 1 | 11 | 2024-02-01 08:30:00 | 1-1 |
| 2 | 12 | 2024-02-01 08:05:00 | 2-1 |
| 2 | 13 | 2024-02-01 09:00:00 | 2-2 |
User 1's two events are exactly 30 minutes (1800 seconds) apart, which is not more than 1800, so both stay in session 1-1. User 2's events are 55 minutes (3300 seconds) apart, so the second one starts session 2-2.
Constraints and Clarifications
-
event_id
is unique.
user_id
is between 1 and 100,000.
event_time
is never NULL.
-
The gap is measured from the same user's previous event in the order above, not from the first event of the session. A session can therefore last much longer than 30 minutes if events keep arriving.
-
Two events of the same user with the same
event_time
are 0 seconds apart and share a session. The one with the smaller
event_id
comes first.
-
Each user's first event starts session 1. Session numbers are counted per user, so different users' sessions are numbered independently.