Return the 2 most recent events per user, ranked by event_time descending with ties broken by the larger event_id first. Output user_id, event_id, event_type, event_time and recency_rank (1 is the most recent event, 2 is the next). Users with a single event appear with just that row.
Input Table(s)
users
| Column | Type | Meaning |
|---|
| user_id | INT | User identifier |
| user_name | VARCHAR(100) | Display name, not null |
Key: user_id is the primary key.
events
| Column | Type | Meaning |
|---|
| event_id | INT | Event identifier |
| user_id | INT | User who produced the event, not null |
| event_type | VARCHAR(50) | Kind of event, such as login or click, not null |
| event_time | TIMESTAMP | When the event happened, not null |
Keys: event_id is the primary key. user_id is a foreign key to users(user_id).
Output Contract
| Column | Meaning |
|---|
| user_id | The user |
| event_id | One of that user's two most recent events |
| event_type | Type of that event |
| event_time | Time of that event |
| recency_rank | 1 for the user's most recent event, 2 for the next one |
Sort by user_id ascending, then recency_rank ascending. The pair (user_id, recency_rank) is unique. No rounding is involved.
Example
users
| user_id | user_name |
|---|
| 1 | Alice |
| 2 | Bob |
events
| event_id | user_id | event_type | event_time |
|---|
| 101 | 1 | login | 2024-01-10 08:00:00 |
| 102 | 1 | click | 2024-01-11 09:30:00 |
| 103 | 1 | logout | 2024-01-12 18:00:00 |
| 104 | 2 | login | 2024-01-09 07:00:00 |
Expected output:
| user_id | event_id | event_type | event_time | recency_rank |
|---|
| 1 | 103 | logout | 2024-01-12 18:00:00 | 1 |
| 1 | 102 | click | 2024-01-11 09:30:00 | 2 |
| 2 | 104 | login | 2024-01-09 07:00:00 | 1 |
Alice has three events. Only her two most recent (logout on 2024-01-12 and click on 2024-01-11) are returned, with ranks 1 and 2. Bob has a single event, returned with rank 1.
Constraints and Clarifications
-
There are 1 to 10,000 users and 1 to 100,000 events.
-
event_id
is unique and
event_time
is never NULL.
-
Two events of the same user can share the same
event_time
. The one with the larger
event_id
gets the better (smaller) rank.
-
A user with exactly one event returns one row with
recency_rank
1. A user with no events returns no rows.
-
user_name
is not part of the output.