For each user, return username, first_active_date (the earliest activity_date with activity_type = 'login') and last_inactive_date (the latest activity_date with activity_type = 'logout'). Include only users with at least one login and at least one logout. Order by user_id ascending.
Input Table(s)
users
| Column | Type | Meaning |
|---|
| user_id | INT | User identifier, primary key |
| username | VARCHAR(50) | The user's name, NOT NULL |
activity_log
| Column | Type | Meaning |
|---|
| log_id | INT | Log row identifier, primary key |
| user_id | INT | The user who acted, foreign key to users.user_id |
| activity_type | VARCHAR(10) | 'login' or 'logout', NOT NULL |
| activity_date | DATE | Day of the activity, NOT NULL |
Keys: users.user_id and activity_log.log_id are primary keys. activity_log.user_id references users.user_id.
Output Contract
| Column | Type | Meaning |
|---|
| username | VARCHAR | The user's username |
| first_active_date | DATE | Earliest activity_date among the user's 'login' rows |
| last_inactive_date | DATE | Latest activity_date among the user's 'logout' rows |
Return one row per user who has at least one login and at least one logout, ordered by user_id ascending. user_id is not an output column, but it is unique, so the order is fully determined. No rounding applies.
Example
users
| user_id | username |
|---|
| 1 | alice |
| 2 | bob |
| 3 | carol |
| 4 | dave |
| 5 | erin |
activity_log
| log_id | user_id | activity_type | activity_date |
|---|
| 1 | 1 | login | 2024-01-05 |
| 2 | 1 | logout | 2024-01-05 |
| 3 | 1 | login | 2024-01-02 |
| 4 | 1 | logout | 2024-01-09 |
| 5 | 2 | login | 2024-01-03 |
| 6 | 3 | logout | 2024-01-04 |
| 7 | 3 | login | 2024-01-06 |
| 8 | 4 | logout | 2024-01-06 |
Expected output:
| username | first_active_date | last_inactive_date |
|---|
| alice | 2024-01-02 | 2024-01-09 |
| carol | 2024-01-06 | 2024-01-04 |
Alice's earliest login is 2024-01-02 and her latest logout is 2024-01-09. Carol's only logout comes before her only login, and both dates are still reported. Bob has no logout, Dave has no login and Erin has no activity, so none of them appear.
Constraints and Clarifications
-
activity_log
has at most
104
rows.
-
activity_type
is always
'login'
or
'logout'
, and no column holds NULL.
-
Every
activity_log.user_id
references a valid user.
-
A user can log in or out many times, including several times on the same date. Only the earliest login date and the latest logout date matter.
-
The two dates are computed independently. Logins are not paired with logouts, so
last_inactive_date
may be earlier than
first_active_date
.
-
username
is not declared unique. Two users with the same name produce two separate rows.