# 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    |
+---------------+---------+
| 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)
``````