我正在进行一些分组并尝试以下方法:
declare @toErase table
(
Group1 int,
Num int,
Denom int
)
insert into @toErase select 1, 1, 5
insert into @toErase select 1, 3, 36
insert into @toErase select 1, 4, null
insert into @toErase select 1, null, 15
select sum(num + denom) from @toErase group by group1
-- Returns 45
Run Code Online (Sandbox Code Playgroud)
这将返回45. 45来自哪里?
另一方面,select sum(num) + sum(denom) from @toErase group by group1返回正确的值.
谢谢.
它来自:
row1: 1+5 = 6
row2: 3+36 = 39
row3: 4+null = null
row4: null+15 = null
Run Code Online (Sandbox Code Playgroud)
SUM 忽略空值,结果是6 + 39 = 45.
使用ISNULL或COALESCE用默认值(可能为0)替换空值,从而在+操作中有效地忽略它们.