今天做了一个统计月均饱和度的问题,有12个月份,若干部门,测试数据的时候加了11月和12月的数据。
当时想的是先求和:
select a.AR_DeptCode, sum (case when DATEPART(mm,AR_NoteTime)=11 then ar_ratio else 0 end) as '11',
sum(case when DATEPART(mm,AR_NoteTime)=12 then ar_ratio else 0 end) as '12'
from AttendRecord a group by AR_DeptCode
结果出来了,但不知道每个部门每个月份有多少人合计了,然后把sum改成avg,又出现了问题:
求平均数的时候每个部门都除以同样的个数了。。。也不行
最后冥思苦想终于发现问题了(下午脑子不好。。。)
我把else去掉就OK了,没有的数据就不加了,这样求平均的时候就没有多余的个数了:
select a.AR_DeptCode,
avg (case when DATEPART(mm,AR_NoteTime)=1 then ar_ratio end) as '1',
avg (case when DATEPART(mm,AR_NoteTime)=2 then ar_ratio end) as '2',
avg (case when DATEPART(mm,AR_NoteTime)=3 then ar_ratio end) as '3',
avg (case when DATEPART(mm,AR_NoteTime)=4 then ar_ratio end) as '4',
avg (case when DATEPART(mm,AR_NoteTime)=5 then ar_ratio end) as '5',
avg (case when DATEPART(mm,AR_NoteTime)=6 then ar_ratio end) as '6',
avg (case when DATEPART(mm,AR_NoteTime)=7 then ar_ratio end) as '7',
avg (case when DATEPART(mm,AR_NoteTime)=8 then ar_ratio end) as '8',
avg (case when DATEPART(mm,AR_NoteTime)=9 then ar_ratio end) as '9',
avg (case when DATEPART(mm,AR_NoteTime)=10 then ar_ratio end) as '10',
avg (case when DATEPART(mm,AR_NoteTime)=11 then ar_ratio end) as '11',
avg (case when DATEPART(mm,AR_NoteTime)=12 then ar_ratio end) as '12'
from AttendRecord a group by AR_DeptCode
完美!!!