sql聚合查询SUM

来源:百度知道 编辑:UC知道 时间:2024/07/04 13:00:05
请问 select (sum(a)-sum(b)) as c from t1
和 select (sum(a-b)) as c from t1 有什么区别么?
为什么结果不一样?

有null时会不一样

如:
set nocount on ;

declare @t table(a int,b int)
insert @t
select 1,null union all
select null,100 union all
select 100,50

select sum(a)-sum(b) from @t
select sum(a-b) from @t

-----------
-49

-----------
50

如果a或者b有负值
出来的结果就不一样了

判断下空吧。
sum(nvl(a,0))

当然有区别上面是整列的,而下面的是出错的过不了语句