2017-07-17 104 views
0

我写了一个查询,增加了上周工作时间。如何返回sum函数的空值?

select laborcode, sum(regularhrs) as TOTALACTUALS 
from labtrans 
where (laborcode='a' OR laborcode='b' OR laborcode='c' OR laborcode='d' 
OR laborcode='e' OR laborcode='f') and (startdate BETWEEN DATEADD(day, DATEDIFF(day, 7, getdate()), 0) and DATEADD(day, DATEDIFF(day, 0, getdate()), 0)) 
group by laborcode; 

比方说,劳动“a”有从上周0小时,我的结果是:

b 25,5 
c 37,25 
d 24 
e 48,5 
f 25,5 

,但我希望得到劳动“是”太多,但与空值。例如:

a 0 (or null) 
b 25,5 
c 37,25 
d 24 
e 48,5 
f 25,5 
+0

试试这个isnull(sum(name),0) – Muj

+0

你有你的劳工代码表吗? – Jens

+1

@Muj这是行不通的,因为你没有得到一行劳动代码a – Jens

回答

0

使用条件SUM

select laborcode 
    , sum(CASE WHEN startdate BETWEEN DATEADD(day, DATEDIFF(day, 7, getdate()), 0) and DATEADD(day, DATEDIFF(day, 0, getdate()), 0) THEN regularhrs END) as TOTALACTUALS 
from labtrans 
where laborcode in('a','b','c','d','e','f') 
group by laborcode; 

或者左加入到predifined列表

SELECT l.laborcode, sum(d.regularhrs) as TOTALACTUALS 
from (
    values ('a'),('b'),('c'),('d'),('e'),('f') 
    ) l(laborcode) 
left join labtrans d on d.laborcode = l.laborcode and (d.startdate BETWEEN DATEADD(day, DATEDIFF(day, 7, getdate()), 0) and DATEADD(day, DATEDIFF(day, 0, getdate()), 0)) 
group by l.laborcode 
+0

第一个工作,很容易理解,谢谢。 –

0

左加入您的值进行分组,以labourcodes列表:

select distinct b.labourcode, coalesce(a.TotalHours,0) as TotalHours 
from labtrans b 
left join 
(
    select a.laborcode, sum(a.regularhrs) as 
    from labtrans a 
    where a.labourcode in ('a','b','c','d','e','f') 
    and a.startdate BETWEEN DATEADD(day, DATEDIFF(day, 7, getdate()), 0) and DATEADD(day, DATEDIFF(day, 0, getdate()), 0) 
    group by a.laborcode 
) 
on a.labourcode = b.labourcode 
+0

如果劳动法是动态的先生,怎么样? – Muj

+0

@Muj then'在(@labourcode)'中的a.labourcode' – JohnHC