我需要在多年内创建每周平均数。例如,如果我有:
select w.weekno, isNULL(AVG(quantity),0) as 'mcount'
from weeks w
left join sampledates sd ON w.weekNo = datepart(wk,sd.sampledate)
inner join sampledate_species_location ssdl ON sd.sampledateid = ssdl.sampledateid
inner join locations l ON ssdl.locationid = l.locationid
inner join species s ON ssdl.speciesid = s.speciesid
where year(sd.sampledate) = datepart(yy,getDate())
and l.locationid = 8
and l.generalarea = 'Western'
group by w.weekno
order by w.weekno
我的结果需要的是:
WEEK MCOUNT
17 0
18 6
19 7
20 8
21 9
22 5
23 0
24 8
我创建了一个名为周的表,周数为17-41周,因为这周没有希望将其加入结果将包括我没有数量的周数,但这不起作用。我也必须做同样的查询,但对于前几年,我不确定我将按照相同的格式按星期平均多年。
答案 0 :(得分:1)
问题在于您的where
子句和inner join
。您需要为所有表继续left outer join
s。然后,where
条件必须在on
子句中(否则left joins
会变为inner join
s):
select w.weekno, isNULL(AVG(quantity),0) as 'mcount'
from weeks w left join
sampledates sd
ON w.weekNo = datepart(wk, sd.sampledate) and
year(sd.sampledate) = datepart(yy, getDate()) left join
sampledate_species_location ssdl
ON sd.sampledateid = ssdl.sampledateid left join
locations l
ON ssdl.locationid = l.locationid and
l.locationid = 8 and
l.generalarea = 'Western' left join
species s
ON ssdl.speciesid = s.speciesid
group by w.weekno
order by w.weekno;