我想按部门和日期创建工作时间轴。
我有一个SQL喜欢
select department,sum(workinghours),date group by department,date.
然后我写一个数据透视
select * from(
select department,sum(workinghours) as hours,date group by department,date
)as RC
PIVOT
(
sum(hours) for date
)as P
但是这返回很多空值。所以我将枢纽更新为
select * from(
select department,sum(workinghours) as hours,date group by department,date
)as RC
PIVOT
(
(case when sum(hours) is null then 0 else sum(hours) end) for date
)as P
然后它有错误。 我不明白为什么,有人可以帮忙吗?
答案 0 :(得分:2)
您需要用null
中的某些特定值替换sum
。由于我替换了0而不是null
:
create table #t
(
Id int identity (1,1),
Department varchar (100),
WorkingHours int ,
Date datetime
)
Insert into #t (Department,WorkingHours,Date)
Select '1','10',GETDATE ()-1
Insert into #t (Department,WorkingHours,Date)
Select '1','20',GETDATE ()-1
Insert into #t (Department,WorkingHours,Date)
Select '1',null,GETDATE ()
select * from #t
select * from(
select department,sum(ISNULL(workinghours,0)) as hours,
cast (Year(date) as varchar) date
from #t
group by department,date
)as RC
PIVOT
(
sum(hours ) for date IN ([2018])
)as P
答案 1 :(得分:0)
请尝试下面的例子求和:
select * from(
select department,sum(workinghours) as hours,date group by department,date
)as RC
PIVOT
(
sum(case when hours is null then 0 else hours end) for date
)as P