摘要 - 每小时,间隔时间

时间:2017-05-31 12:45:49

标签: sql sql-server sql-server-2008 tsql pivot

我有以下数据:

enter image description here

这意味着, 2h 8h 之间需要 10人来处理任务1 等。

如何在所有正在运行的任务中创建每小时所需工人总结的时间表?像这样:

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用小时数,计数表和数据透视表来获取此信息,如下所示:

select ISNULL([1],0) as [1:00:00], [2] as [2:00:00],[3] as [3:00:00], [4] as [4:00:00],[5] as [5:00:00]
,[6] as [6:00:00],[7] as [7:00:00],[8] as [8:00:00],ISNULL([9],0) as [9:00:00]
from (
    select Hrs= Datepart(hour,RowN),SmPeople= sum(people) from Yourtask
    cross apply (
        select top (datediff(hour, [start],[end])+1) RowN= DateAdd(hour, row_number() over (order by (Select null))-1, [Start]) 
            from master..spt_values n1, master..spt_values n2
    ) a
    group by Datepart(hour,RowN)
) CalcuatedPeople
pivot (max(SmPeople) for hrs in ([1],[2],[3],[4],[5],[6],[7],[8],[9])) p 

输出如下:

+---------+---------+---------+---------+---------+---------+---------+---------+---------+
| 1:00:00 | 2:00:00 | 3:00:00 | 4:00:00 | 5:00:00 | 6:00:00 | 7:00:00 | 8:00:00 | 9:00:00 |
+---------+---------+---------+---------+---------+---------+---------+---------+---------+
|       0 |      15 |      23 |      33 |      33 |      25 |      15 |      15 |       0 |
+---------+---------+---------+---------+---------+---------+---------+---------+---------+

答案 1 :(得分:2)

与CROSS APPLY一起使用的简单条件聚合应该可以解决问题

Declare @YourTable table ([Task] int,[Start] datetime,[End] datetime,[People] int)
Insert Into @YourTable values
 (1,'2017-03-17 02:00:00','2017-03-17 08:00:00',10)
,(2,'2017-03-17 02:00:00','2017-03-17 08:00:00',5)
,(3,'2017-03-17 03:00:00','2017-03-17 05:00:00',8)
,(4,'2017-03-17 04:00:00','2017-03-17 06:00:00',10)

Select [01:00] = sum(case when DatePart(HOUR,D)=1 then People else 0 end)
      ,[02:00] = sum(case when DatePart(HOUR,D)=2 then People else 0 end)
      ,[03:00] = sum(case when DatePart(HOUR,D)=3 then People else 0 end)
      ,[04:00] = sum(case when DatePart(HOUR,D)=4 then People else 0 end)
      ,[05:00] = sum(case when DatePart(HOUR,D)=5 then People else 0 end)
      ,[06:00] = sum(case when DatePart(HOUR,D)=6 then People else 0 end)
      ,[07:00] = sum(case when DatePart(HOUR,D)=7 then People else 0 end)
      ,[08:00] = sum(case when DatePart(HOUR,D)=8 then People else 0 end)
      ,[09:00] = sum(case when DatePart(HOUR,D)=9 then People else 0 end)
 From  @YourTable
 Cross Apply (Select Top (DateDiff(HOUR,[Start],[End])+1) D=DateAdd(HOUR,-1+Row_Number() Over (Order By (Select Null)),[Start]) 
                 From  master..spt_values n1,master..spt_values n2 
              ) B

<强>返回

01:00   02:00   03:00   04:00   05:00   06:00   07:00   08:00   09:00
0       15      23      33      33      25      15      15      0