计算SQL中的连续班次和天数

时间:2016-11-23 01:24:17

标签: sql sql-server sql-server-2012 recursive-query gaps-and-islands

我正在尝试显示团队工作的连续班次和天数。我已经尝试了很多解决方案,但却无法做到这一点。

数据是日期,班次,船员。有一个日夜班和3名工作人员。 ConsecutiveShift和ConsecutiveDay是我想要制作的领域。输出将用于根据连续轮班/工作天数查看生产率。

非常感谢任何帮助

{{1}}

期望输出 - 前3列是原始数据,第4列和第5列是我要生成的计数

2 个答案:

答案 0 :(得分:0)

以下查询应该可以使用窗口函数:

With cte As (
    Select DateOp, Shift, Crew,
        DateDiff(Day, DateOp, '2016-01-01') + Row_Number() Over (Partition By Crew, Shift Order By DateOp) As ShiftIsland,
        DateDiff(Day, DateOp, '2016-01-01') + Row_Number() Over (Partition By Crew Order By DateOp) As DayIsland
      From [YourTable])      
Select DateOp, Shift, Crew,
    Row_Number() Over (Partition By Crew, Shift, ShiftIsland Order By DateOp) As ConsecutiveShifts,
    Row_Number() Over (Partition By Crew, DayIsland Order By DateOp) As ConsecutiveDays
  From cte
  Order By Crew, DateOp, Shift;

答案 1 :(得分:-1)

我认为这是一个基本的date_object。对于您提供的数据:

row_number()

这至少会返回您问题中的数据。