Given a table UserActivity that contains information about user activities over time periods, write a SQL query to find the second most recent activity for each user.
Special Rule: If a user has only one activity, return that single activity.
Each activity has a startDate and endDate, and users cannot perform multiple activities simultaneously. The most recent activity is determined by the latest startDate.
Table Schema
| Column Name | Type | Description |
|---|---|---|
username
|
varchar | Username of the person performing the activity |
activity
|
varchar | Name of the activity performed |
startDate
|
date | Start date of the activity |
endDate
|
date | End date of the activity |
Input & Output
| username | activity | startDate | endDate |
|---|---|---|---|
| Alice | Travel | 2020-02-11 | 2020-02-20 |
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Alice | Study | 2020-02-24 | 2020-02-25 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
| username | activity | startDate | endDate |
|---|---|---|---|
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
Alice has 3 activities. Ranked by startDate: Study (1st), Dancing (2nd), Travel (3rd). We select Dancing as the second most recent. Bob has only 1 activity, so we return that single Travel activity.
| username | activity | startDate | endDate |
|---|---|---|---|
| Alice | Travel | 2020-02-11 | 2020-02-20 |
| Bob | Study | 2020-02-15 | 2020-02-18 |
| username | activity | startDate | endDate |
|---|---|---|---|
| Alice | Travel | 2020-02-11 | 2020-02-20 |
| Bob | Study | 2020-02-15 | 2020-02-18 |
Both Alice and Bob have only one activity each. According to the rule, when a user has only one activity, we return that activity as their 'second most recent'.
| username | activity | startDate | endDate |
|---|---|---|---|
| Alice | Travel | 2020-02-11 | 2020-02-20 |
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Bob | Study | 2020-02-15 | 2020-02-18 |
| Charlie | Swimming | 2020-02-10 | 2020-02-12 |
| Charlie | Reading | 2020-02-13 | 2020-02-15 |
| Charlie | Cooking | 2020-02-16 | 2020-02-18 |
| username | activity | startDate | endDate |
|---|---|---|---|
| Alice | Travel | 2020-02-11 | 2020-02-20 |
| Bob | Study | 2020-02-15 | 2020-02-18 |
| Charlie | Reading | 2020-02-13 | 2020-02-15 |
Alice has 2 activities - Dancing is most recent, Travel is second most recent. Bob has 1 activity - return Study. Charlie has 3 activities - Cooking is most recent, Reading is second most recent.
Constraints
-
usernameandactivityare non-empty strings -
startDate ≤ endDatefor all activities - Users cannot perform multiple activities simultaneously
- Table may contain duplicate rows