Get The Second Most Recent Activity Problem
Description
LeetCode Problem 1369.
Table: UserActivity
1
2
3
4
5
6
7
8
9
10
11
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| username | varchar |
| activity | varchar |
| startDate | Date |
| endDate | Date |
+---------------+---------+
This table does not contain primary key.
This table contain information about the activity performed of each user in a period of time.
A person with username performed a activity from startDate to endDate.
Write an SQL query to show the second most recent activity of each user.
If the user only has one activity, return that one.
A user can’t perform more than one activity at the same time. Return the result table in any order.
The query result format is in the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
UserActivity table:
+------------+--------------+-------------+-------------+
| username | activity | startDate | endDate |
+------------+--------------+-------------+-------------+
| Alice | Travel | 2020-02-12 | 2020-02-20 |
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Alice | Travel | 2020-02-24 | 2020-02-28 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
+------------+--------------+-------------+-------------+
Result table:
+------------+--------------+-------------+-------------+
| username | activity | startDate | endDate |
+------------+--------------+-------------+-------------+
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
+------------+--------------+-------------+-------------+
The most recent activity of Alice is Travel from 2020-02-24 to 2020-02-28, before that she was dancing from 2020-02-21 to 2020-02-23.
Bob only has one record, we just take that one.
MySQL Solution
1
2
3
4
5
6
7
select distinct username, activity, startDate, endDate
from
(select u.*,
rank() over (partition by username order by startDate desc) as rnk,
count(activity) over (partition by username) as num
from UserActivity u) t
where (num <> 1 and rnk = 2) or (num = 1 and rnk = 1)
LeetCode Database - Hard
LeetCode 185
LeetCode 262
LeetCode 569
LeetCode 571
LeetCode 579
LeetCode 601
LeetCode 615
LeetCode 618
LeetCode 1097
LeetCode 1127
LeetCode 1159
LeetCode 1194
LeetCode 1225
LeetCode 1336
LeetCode 1369
LeetCode 1384
LeetCode 1412
LeetCode 1479
LeetCode 1635
LeetCode 1645
LeetCode 1651
LeetCode 1767
LeetCode 1892
LeetCode 1917
LeetCode 1919
LeetCode 1972
More LeetCode Database
MySQL Tutorials