列表

详情


1369. 获取最近第二次的活动

表: UserActivity

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| username      | varchar |
| activity      | varchar |
| startDate     | Date    |
| endDate       | Date    |
+---------------+---------+
该表可能有重复的行
该表包含每个用户在一段时间内进行的活动的信息
名为 username 的用户在 startDate 到 endDate 日内有一次活动

 

编写解决方案展示每一位用户 最近第二次 的活动

如果用户仅有一次活动,返回该活动

一个用户不能同时进行超过一项活动,以 任意 顺序返回结果

下面是返回结果格式的例子。

 

示例 1:

输入:
UserActivity 表:
+------------+--------------+-------------+-------------+
| 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  |
+------------+--------------+-------------+-------------+
输出:
+------------+--------------+-------------+-------------+
| username   | activity     | startDate   | endDate     |
+------------+--------------+-------------+-------------+
| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
+------------+--------------+-------------+-------------+
解释:
Alice 最近一次的活动是从 2020-02-24 到 2020-02-28 的旅行, 在此之前的 2020-02-21 到 2020-02-23 她进行了舞蹈
Bob 只有一条记录,我们就取这条记录

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
# Write your MySQL query statement below

mysql 解法, 执行用时: 247 ms, 内存消耗: 0 B, 提交时间: 2023-10-15 22:56:30

select u.*
from UserActivity u
where (u.username, u.startDate) in 
(
    select a.username, max(a.startDate) 
    from UserActivity a 
    where (a.username, a.startDate) not in (
        select b.username, max(b.startDate)
        from UserActivity b
        group by b.username
        having count(b.username) > 1
    ) 
    group by a.username
)

mysql 解法, 执行用时: 276 ms, 内存消耗: 0 B, 提交时间: 2023-10-15 22:56:17

select A.username,A.activity,A.startDate,A.endDate
    from (select a.*,
                 COUNT(1) over(partition by a.username) cn,
                 row_number() over(partition by a.username order by a.startdate desc) rn
            from UserActivity a) A
   WHERe A.cn = '1'
      or A.rn = '2'

上一题