在一次使用sql语句用SUM求和时发现统计出来的结果,跟正确的结果不一致。后来发现,是因为有的字段为NULL造成的。
SQL示例:select sum(filed1)+sum(filed2)+sum(filed3) from tableTest
解决办法:
Oracle
select nvl(sum(filed1),0)+nvl(sum(filed2),0)+nvl(sum(filed3),0) from tableTest
SqlServer
select ISNULL(sum(filed1),0)+ISNULL(sum(filed2),0)+ISNULL(sum(filed3),0) from tableTest
除了sum求和存在这个问题,我想其他的像求平均值什么的,应该也会存在类似的问题,以后加以注意。