I wrote a query which adds work hours of labors from last week.
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;
Let's say labor "a" has 0 hours from last week, my result is:
b 25,5
c 37,25
d 24
e 48,5
f 25,5
but I want to get labor "a" too but with null value. For example:
a 0 (or null)
b 25,5
c 37,25
d 24
e 48,5
f 25,5
Left join your grouped by values to a list of 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
Using conditional 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;
Or left join to a predifined list
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.