首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL求一行中值不为零的个数解决方法

2012-01-09 
SQL求一行中值不为零的个数SQL求一行中值不为零的个数.A表的的资料如下Vendor_CodeMonth3Month4Month5Mont

SQL求一行中值不为零的个数
SQL求一行中值不为零的个数.
A表的的资料如下
Vendor_Code   Month3Month4Month5Month6Average  
vd0003         06052056
vd0001         060525054
vd0002         06052056

说明:我已经有各个月的值(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

热点排行