查询 Return 每个员工的所有工作周期和成本代码

Query to Return all Working Periods per Employee and Cost Code

我有显示员工、成本代码和周末(星期日)的数据。 WeekEnd 是工作周的最后一天,从周一到周日:

EmpID   CostCode   WeekEnd
=============================
    1   1          01/02/2022  
    1   1          01/09/2022
    Employee skipped working in week of 1/16/2022 ...
    1   1          01/23/2022
    1   1          01/30/2022
    1   2          02/06/2022 
    1   3          02/13/2022
    1   3          02/20/2022

需要得到这样的结果:

EmpID   CostCode   FirstWeekEnd    LastWeekEnd
==============================================
    1   1          01/02/2022      01/09/2022
    1   1          01/23/2022      01/30/2022
    1   2          02/06/2022      02/06/2022
    1   3          02/13/2022      02/20/2022

我需要获取员工按成本代码工作的所有期间(开始 - 结束)?

可以通过计算连续周的排名来解决。

然后也根据该排名进行汇总。

SELECT EmpId, CostCode
, MIN(WeekEnd) AS FirstWeekEnd
, MAX(WeekEnd) AS LastWeekEnd
FROM
(
  SELECT *
  , SUM(Flag) OVER (PARTITION BY EmpID ORDER BY WeekEnd) AS Rnk
  FROM
  (
    SELECT *
    , IIF(7>=DATEDIFF(day, LAG(WeekEnd) OVER (PARTITION BY EmpID ORDER BY WeekEnd), WeekEnd),0,1) AS Flag
    FROM your_table
  ) q1
) q2
GROUP BY EmpId, CostCode, Rnk
ORDER BY EmpId, FirstWeekEnd;
EmpId CostCode FirstWeekEnd LastWeekEnd
1 1 2022-01-02 2022-01-09
1 1 2022-01-23 2022-01-30
1 2 2022-02-06 2022-02-06
1 3 2022-02-13 2022-02-20

测试 db<>fiddle here