An activity log table holds repeated events for the same user and activity type. For each (user_id, activity_type) group, keep only the row with the largest activity_time, breaking ties by the largest log_id. Return log_id, user_id, activity_type and activity_time, sorted by user_id, activity_type and log_id, all ascending.
Input Table(s)
activity_logs
| Column | Type | Meaning |
|---|
| log_id | INT | Log record identifier. Primary key. |
| user_id | INT | User who performed the activity. NOT NULL. |
| activity_type | VARCHAR(50) | Kind of activity, such as login or logout. NOT NULL. |
| activity_time | DATETIME (TIMESTAMP in PostgreSQL) | When the activity happened. NOT NULL. |
Keys: log_id is the primary key. Nothing stops several rows from sharing the same user_id, activity_type and activity_time.
Output Contract
| Column | Type | Meaning |
|---|
| log_id | INT | The surviving row's log_id. |
| user_id | INT | The group's user. |
| activity_type | VARCHAR | The group's activity type. |
| activity_time | TIMESTAMP | The surviving row's activity_time, which is the latest time in the group. |
Return exactly one row per (user_id, activity_type) pair. Order by user_id ascending, then activity_type ascending, then log_id ascending.
Example
activity_logs
| log_id | user_id | activity_type | activity_time |
|---|
| 1 | 100 | login | 2024-01-10 08:00:00 |
| 2 | 100 | login | 2024-01-12 09:30:00 |
| 3 | 100 | logout | 2024-01-12 17:00:00 |
| 4 | 200 | login | 2024-01-11 07:45:00 |
| 5 | 200 | login | 2024-01-15 10:00:00 |
Expected result:
| log_id | user_id | activity_type | activity_time |
|---|
| 2 | 100 | login | 2024-01-12 09:30:00 |
| 3 | 100 | logout | 2024-01-12 17:00:00 |
| 5 | 200 | login | 2024-01-15 10:00:00 |
User 100 has two logins, and row 2 is the later one. Their single logout (row 3) survives as is. User 200's later login is row 5.
A second example with a tie on time:
| log_id | user_id | activity_type | activity_time |
|---|
| 6 | 300 | purchase | 2024-01-20 12:00:00 |
| 7 | 300 | purchase | 2024-01-20 12:00:00 |
| 8 | 300 | purchase | 2024-01-18 09:00:00 |
Expected result:
| log_id | user_id | activity_type | activity_time |
|---|
| 7 | 300 | purchase | 2024-01-20 12:00:00 |
Rows 6 and 7 share the latest time, so the larger log_id, 7, wins. Row 8 is older and drops out even though it has the largest log_id in the group.
Constraints and Clarifications
-
The table has between 1 and 100,000 rows.
-
activity_type
is a non-empty string of at most 50 characters. Group on it exactly as stored, so
login
and
Login
would be different groups.
-
No column contains NULLs.
-
Several rows of a group can share the latest
activity_time
. Only the one with the largest
log_id
among them is returned.