【问题标题】:SQL - Group vacations in a table based on a holidaysSQL - 根据假期在表中分组假期
【发布时间】:2022-06-22 00:04:11
【问题描述】:

这是员工休假表中的示例数据。

Emp_id   Vacation_Start_Date    Vacation_End_Date Public_Hday
1234         06/01/2022            06/07/2022       null
1234         06/08/2022            06/14/2022       null
1234         06/15/2022            06/19/2022       06/17/2022
1234         06/20/2022            06/23/2022       null
1234         06/24/2022            06/28/2022       null
1234         06/29/2022            07/02/2022       06/30/2022
1234         07/03/2022            07/07/2022       null
1234         07/08/2022            07/12/2022       null
1234         07/13/2022            07/17/2022       07/15/2022
1234         07/18/2022            07/22/2022       null

我想根据公共假期对这些假期进行分组(假设所有假期都是连续的)。这是我想要得到的输出。

   Emp_id   Vacation_Start_Date    Vacation_End_Date  Public_Hday    Group
    1234         06/01/2022            06/07/2022       null           0
    1234         06/08/2022            06/14/2022       null           0
    1234         06/15/2022            06/19/2022       06/17/2022     1
    1234         06/20/2022            06/23/2022       null           1 
    1234         06/24/2022            06/28/2022       null           1
    1234         06/29/2022            07/02/2022       06/30/2022     2
    1234         07/03/2022            07/07/2022       null           2
    1234         07/08/2022            07/12/2022       null           2
    1234         07/13/2022            07/17/2022       07/15/2022     3
    1234         07/18/2022            07/22/2022       null           3

这是我尝试过的代码

Select *, dense_rank() over (partition by Emp_id order by Public_Hday) - 1 AS Group from Emp_Vacation.

但是,它只为 Public_Hday 不为空的假期提供了预期的组值。如何将组值获取到其他假期。

【问题讨论】:

  • MySQL SQL Server;您真正使用的是什么 RDBMS?
  • 您的样本数据与预期输出有何不同?

标签: sql


【解决方案1】:

你可以使用条件 sum() over()

Select * 
      ,Grp = sum( case when [Public_Hday] is null then 0 else 1 end ) over (partition by [Emp_id] order by [Vacation_Start_Date])
from YourTable

结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多