For each session_id in page_views, return the first and last page visited (ordered by event_time) and the session duration. Use the window functions FIRST_VALUE and LAST_VALUE to pick the pages. Return exactly one row per session.
Input Table(s)
page_views
| Column | Type | Meaning |
|---|
| view_id | INT | Page view identifier |
| session_id | INT | Session the view belongs to |
| page | VARCHAR(50) | Page path that was viewed |
| event_time | TIMESTAMP | When the view happened (DATETIME in MySQL) |
Primary key: view_id.
Output Contract
-
Columns, in this order:
session_id
,
first_page
,
last_page
,
duration_minutes
.
-
Exactly one row per distinct
session_id
.
-
first_page
is the
page
of the session's earliest
event_time
, and
last_page
is the
page
of its latest
event_time
.
-
duration_minutes
is the number of minutes between the earliest and latest
event_time
of the session, rounded to 2 decimal places.
-
Order by
session_id
ascending.
Example
Input page_views:
| view_id | session_id | page | event_time |
|---|
| 1 | 100 | /home | 2024-01-01 09:00:00 |
| 2 | 100 | /products | 2024-01-01 09:02:00 |
| 3 | 100 | /checkout | 2024-01-01 09:05:00 |
| 4 | 200 | /landing | 2024-01-01 10:00:00 |
Expected output:
| session_id | first_page | last_page | duration_minutes |
|---|
| 100 | /home | /checkout | 5.00 |
| 200 | /landing | /landing | 0.00 |
Session 100 starts at /home at 09:00 and ends at /checkout at 09:05, so it spans 5 minutes. Session 200 has a single event, so its first and last page are both /landing and its duration is 0.00.
Constraints and Clarifications
-
page_views
has between 1 and 10,000 rows.
-
page
values are non-NULL strings of at most 50 characters.
-
session_id
and
event_time
are never NULL.
-
event_time
values within a session are distinct, so the first and last page are unique.
-
A single-event session has
first_page
equal to
last_page
and
duration_minutes
equal to
0.00
.
-
The same page can appear several times in one session.