我可以每天计算多行的汇总持续时间吗?

问题描述 投票:0回答:1

我正在创建人力资源缺勤报告。缺勤数据每天作为一行存储在数据库中(列为EmployeeId,缺勤日期,持续时间)。因此,如果我从2020年2月11日(星期二)至2020年2月21日(星期五)下班,表中将有9行:

2020年2月11日-1天

2020年2月12日-1天

2020年2月13日-1天

2020年2月14日-1天

2020年2月17日-1天

2020年2月18日-1天

2020年2月19日-1天

2020年2月20日-1天

2020年2月21日-1天

(请参见下面的屏幕截图)

6 February 2020 - 1 day

HR希望在连续的缺勤期间看到报告中的单个条目:

enter image description here

我的问题是-不使用游标,如何计算SQL中的is(甚至更复杂,因为我必须使用Linq to SQL来执行此操作,但是我可以将其替换为存储过程。请注意,连续数据的标准是相邻工作日(不包括周末和银行假期),我希望我已经明确表示自己……如果没有的话,我们深表歉意。

sql sql-server tsql linq-to-sql gaps-and-islands
1个回答
0
投票

这是一种空白和孤岛的形式。在这种情况下,请使用lag()查看两个休假是否重叠,然后求和:[]

select employee, min(absent_from), max(absent_to)
from (select t.*,
             sum(case when prev_absent_to = dateadd(day, -1, absent_from) then 0 else 1
                 end) over (partition by employee order by absent_to) as grp
      from (select t.*,
                   lag(absent_to) over (partition by employee order by absent_from) as prev_absent_to
            from t
           ) t
     ) t
group by employee, grp;

如果您需要处理假期和周末,那么您需要一个日历表。

© www.soinside.com 2019 - 2024. All rights reserved.