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


    SQL架构

    表: UserActivity

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

    写一条SQL查询展示每一位用户 最近第二次 的活动

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

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

    下面是查询结果格式的例子。

    示例 1:

    1. 输入:
    2. 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 只有一条记录,我们就取这条记录
    1. with e as (select
    2. username,activity, row_number() over(partition by username order by startDate desc) r,startDate,endDate
    3. from
    4. UserActivity)
    5. select username,activity,startDate,endDate from e where r =2
    6. union all
    7. select username,activity,startDate,endDate from e where r = 1 and username not in (select username from e where r =2)
    1. with e as (select
    2. username,activity, row_number() over(partition by username order by startDate desc) r,startDate,endDate
    3. from
    4. UserActivity) # 封装成 虚拟表 减少 重复代码的书写
    5. select username,activity,startDate,endDate from e where r =2 # 选出 第二次 的活动
    6. union all
    7. select username,activity,startDate,endDate from e where r = 1 and username not in (select username from e where r =2)
    8. # 选出 只有 一次 的 活动

    开两个窗:

    1. SELECT u1.username,u1.activity,u1.startDate,u1.endDate
    2. from(
    3. SELECT *,
    4. rank() over(partition by username order by startDate desc ) as 'rank1',
    5. COUNT(*)over(partition by username ) as 'count1'
    6. FROM UserActivity) as u1
    7. WHERE rank1 = 2
    8. or count1 =1

  • 相关阅读:
    开源LC3编解码器测试Demo
    C/C++数据结构——队列
    计算机系统的层次结构
    LoongArch 指令集设计——单周期5条指令exp5
    多容器SSM整合
    通达OA漏洞分析合集
    安防监控EasyCVR视频汇聚平台使用海康SDK播放出现花屏是什么原因?
    GBase 8s手动创建和初始化实例
    Apache Flink 1.12.0 on Yarn(3.1.1) 所遇到的問題
    【Redis】Redis 生产问题。如何确保缓存和数据库数据的一致性? 常见的缓存更新策略?
  • 原文地址:https://blog.csdn.net/m0_69157845/article/details/125477795