返回介绍

solution / 1300-1399 / 1369.Get the Second Most Recent Activity / README_EN

发布于 2024-06-17 01:03:20 字数 2779 浏览 0 评论 0 收藏 0

1369. Get the Second Most Recent Activity

中文文档

Description

Table: UserActivity

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| username    | varchar |
| activity    | varchar |
| startDate   | Date  |
| endDate     | Date  |
+---------------+---------+
This table may contain duplicates rows.
This table contains information about the activity performed by each user in a period of time.
A person with username performed an activity from startDate to endDate.

 

Write a solution to show the second most recent activity of each user.

If the user only has one activity, return that one. A user cannot perform more than one activity at the same time.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
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  |
+------------+--------------+-------------+-------------+
Output: 
+------------+--------------+-------------+-------------+
| username   | activity   | startDate   | endDate   |
+------------+--------------+-------------+-------------+
| Alice    | Dancing    | 2020-02-21  | 2020-02-23  |
| Bob    | Travel     | 2020-02-11  | 2020-02-18  |
+------------+--------------+-------------+-------------+
Explanation: 
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.

Solutions

Solution 1

SELECT
  username,
  activity,
  startdate,
  enddate
FROM
  (
    SELECT
      *,
      RANK() OVER (
        PARTITION BY username
        ORDER BY startdate DESC
      ) AS rk,
      COUNT(username) OVER (PARTITION BY username) AS cnt
    FROM UserActivity
  ) AS a
WHERE a.rk = 2 OR a.cnt = 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文