我写了一个查询,增加了上周的工作时间。
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"但也有空值。例如:
a 0 (or null)
b 25,5
c 37,25
d 24
e 48,5
f 25,5
答案 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
答案 1 :(得分: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;
或者加入一个预定列表
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