Skip to content
Onsite

Sessionise events with a 30-minute inactivity gap

HardP2Coding

Table events:

ColumnType
user_idint
event_timetimestamp

Group each user's events into sessions. A new session starts when the gap since that user's previous event is more than 30 minutes; a gap of exactly 30 minutes stays in the same session. Duplicate timestamps are allowed.

For each session return its number (1, 2, ... per user, in time order), the time of its first event as text YYYY-MM-DD HH24:MI, and the number of events.

Output columns: user_id, session_no, session_start, event_count.

Schema

CREATE TABLE events (
  user_id int NOT NULL,
  event_time timestamp NOT NULL
);

Example 1

Input
user 1 events at 10:00, 10:20, 11:00, 11:15
Output
(1, 1, 10:00, 2), (1, 2, 11:00, 2)
Why
The gap from 10:20 to 11:00 is 40 minutes.

Constraints

  • PostgreSQL dialect.

Hints

PostgreSQL
Run checks the 3 visible tests, Submit all 8.