日期:2014-05-18 浏览次数:20565 次
select year,avg(isnull(m1,0)), avg(isnull(m2,0)), avg(isnull(m3,0)), avg(isnull(m4,0)), avg(isnull(m5,0)), avg(isnull(m6,0)), avg(isnull(m7,0)), avg(isnull(m8,0)), avg(isnull(m9,0)), avg(isnull(m10,0)),avg(isnull(m11,0)),avg(isnull(m12,0)) from tab group by YEAR
------解决方案--------------------
--0为分母的时候需要判断一下 declare @T table ([year] int,m1 int,m2 int, m3 int,m4 int,m5 int,m6 int,m7 int,m8 int,m9 int,m10 int,m11 int,m12 int) insert into @T select 2011,12,13,12,6,7,20,18,14,15,23,22,20 union all select 2011,null,null,2,null,null,21,16,16,21,18,17,19 union all select 2011,14,25,null,5,3,26,21,15,26,20,28,29 union all select 2011,12,13,null,4,null,28,19,12,18,23,16,31 union all select 2012,11,21,4,5,6,7,8,9,10,12,14,15 union all select 2012,19,23,null,null,5,null,6,null,null,null,7,null union all select 2012,22,28,5,6,null,null,null,null,null,null,null,null select [year], m1=cast(sum(isnull(m1,0))*1./count(m1) as decimal(18,2)), m2=cast(sum(isnull(m2,0))*1./count(m2)as decimal(18,2)), m3=cast(sum(isnull(m3,0))*1./count(m3)as decimal(18,2)), m4=cast(sum(isnull(m4,0))*1./count(m4)as decimal(18,2)), m5=cast(sum(isnull(m5,0))*1./count(m5)as decimal(18,2)), m6=cast(sum(isnull(m6,0))*1./count(m6)as decimal(18,2)), m7=cast(sum(isnull(m7,0))*1./count(m7)as decimal(18,2)), m8=cast(sum(isnull(m8,0))*1./count(m8)as decimal(18,2)), m9=cast(sum(isnull(m9,0))*1./count(m9)as decimal(18,2)), m10=cast(sum(isnull(m10,0))*1./count(m10)as decimal(18,2)), m11=cast(sum(isnull(m11,0))*1./count(m11)as decimal(18,2)), m12=cast(sum(isnull(m12,0))*1./count(m12)as decimal(18,2)) from @t group by [year]