日期:2014-05-18  浏览次数:20474 次

SQL求一行中值不为零的个数
SQL求一行中值不为零的个数.
A表的的资料如下
Vendor_Code   Month3 Month4 Month5 Month6 Average  
vd0003         0 60 52 0 56
vd0001         0 60 52 50 54
vd0002         0 60 52 0 56

说明:我已经有各个月的值(Month3,Month4......),现在我要求的是Average的值。
即Average   =   (Month3+Month4+Month5+Month6)/当前行中值不为值的个数。
如第一行值不为零的个数为2(Month4,Month5)
第二行值不为零的个数为3(Month4,Month5,Month6)
第三行值不为零的个数为2(Month4,Month5)
麻烦高手帮忙写一个这样的语法。谢了!



------解决方案--------------------
最笨的办法:
(case when Month3 <> 0 then 1 else 0 end)+(case when Month4 <> 0 then 1 else 0 end)+(case when Month5 <> 0 then 1 else 0 end)+(case when Month6 <> 0 then 1 else 0 end)


------解决方案--------------------
update A表 set average = (month3+month4+month5+month6)/((case month3 when 0 then 0 else 1 end)+(case month4 when 0 then 0 else 1 end)+(case month5 when 0 then 0 else 1 end)+(case month6 when 0 then 0 else 1 end))
------解决方案--------------------
select SIGN(Month3)+SIGN(Month4)+SIGN(Month5)+SIGN(Month6) from #a
如果有负数:
select SIGN(abs(Month3))+SIGN(abs(Month4))+SIGN(abs(Month5))+SIGN(abs(Month6)) from #a
如果都为0 还是用case 好
case when Month3+Month4+Month5+Month6=0 then 0 else (Month3+Month4+Month5+Month6)*1.0/(SIGN(Month3)+SIGN(Month4)+SIGN(Month5)+SIGN(Month6)) end