我有一个 Table tempslotsassignedfordept如下
DEPT ScheduledStartDate ScheduledEndDate TotalSlots
DevEng 2012-07-17 00:00:00.000 2012-08-28 00:00:00.000 39
DevEng 2012-07-17 00:00:00.000 2012-08-31 00:00:00.000 18
DevEng 2012-07-18 00:00:00.000 2012-08-29 00:00:00.000 9
DevEng 2012-07-19 00:00:00.000 2012-08-30 00:00:00.000 40
Prod 2012-07-19 00:00:00.000 2012-08-30 00:00:00.000 8
Rel 2012-07-19 00:00:00.000 2012-08-30 00:00:00.000 19
Rel 2012-07-19 00:00:00.000 2013-08-15 00:00:00.000 1
我必须捕获每个部门的总时隙的上述总和。如果一个部门存在连续 3 天。
如果您看到上表,则有部门 deveng 有连续三个预定开始日期为 2012-07-17、2012-07-18、2012-07-19。
我正在尝试通过使用以下查询来查看结果,请您帮忙查看更多实现以查看确切结果吗?
SELECT Tmain.DepartmentCode,
CONVERT(VARCHAR(20), Tmain.ScheduledStartDate, 101) 'ScheduledStartDate',
SUM(Tmain.TotalSlots) 'Tmain.TotalSlots',T1Sub.TotalSlots 'T1SubTotalSlots', T2Sub.TotalSlots 'T2SubTotalSlots'
FROM tempSlotsAssignedForDept Tmain
INNER JOIN (Select DATEADD(DAY,1,T1.ScheduledStartDate) 'ScheduledStartDate',SUM(T1.TotalSlots) 'TotalSlots'
FROM tempSlotsAssignedForDept T1
INNER JOIN tempSlotsAssignedForDept Tmain
ON (T1.ScheduledStartDate = dateadd(day, -1, tmain.ScheduledStartDate ) and
T1.DepartmentCode = tmain.DepartmentCode)
GROUP BY T1.ScheduledStartDate ) T1Sub
ON Tmain.ScheduledStartDate = T1Sub.ScheduledStartDate
INNER JOIN (Select DATEADD(DAY,2,T2.ScheduledStartDate) 'ScheduledStartDate',SUM(T2.TotalSlots) 'TotalSlots'
FROM tempSlotsAssignedForDept T2
INNER JOIN tempSlotsAssignedForDept Tmain
ON (T2.ScheduledStartDate = dateadd(day, -2, tmain.ScheduledStartDate ) and
T2.DepartmentCode = tmain.DepartmentCode)
GROUP BY T2.ScheduledStartDate ) T2Sub
ON Tmain.ScheduledStartDate = T2Sub.ScheduledStartDate
GROUP BY Tmain.DepartmentCode,Tmain.ScheduledStartDate,T1Sub.TotalSlots , T2Sub.TotalSlots
ORDER BY Tmain.ScheduledStartDate
上面的查询是
DepartmentCode ScheduledStartDate Tmain.TotalSlots T1SubTotalSlots T2SubTotalSlots
DevEng 07/19/2012 40 9 57
Prod 07/19/2012 8 9 57
Rel 07/19/2012 20 9 57
最终结果应如下所示。
因为部门 prod 和 rel 没有 3 天的 schedulestartdate 系列
DepartmentCode ScheduledStartDate Tmain.TotalSlots T1SubTotalSlots T2SubTotalSlots
DevEng 07/19/2012 40 9 57
请帮忙。