[英]Why does Sql Sum of multiple columns containing nulls return incorrect result?
Table containing the following values: 包含以下值的表:
Column1 Column2
1 NULL
NULL 4
2 NULL
NULL 5
3 6
The following query: 以下查询:
SELECT
SUM([Column1] + [Column2] )
FROM [myTable]
returns a value of 9
when it should be returning 21
. 应该返回21
时返回值9
。 Why? 为什么? How does it arrive at the value? 它是如何达到价值的?
I know the SUM can be corrected by adding ISNULL
like so: 我知道可以通过添加ISNULL
来纠正SUM,如下所示:
SELECT
SUM(ISNULL([Column1], 0) + ISNULL([Column2], 0))
FROM [myTable]
but I would like to know the logic behind the value 9
但我想知道价值背后的逻辑9
use COALESCE
to convert null into 0
. 使用COALESCE
将null转换为0
。 ( that's it if you want null values as zero. ) ( 如果你想将空值设为零,那就是它。 )
SELECT SUM(COALESCE(column1,0) + COALESCE(column2,0))
FROM table1
What is the sum of null
and a number, exactly? 究竟是null
和数字的总和是多少? Note where the 9
comes from: the only row which has non-null Column1
and Column2
. 注意9
来自哪里:唯一具有非null Column1
和Column2
。
One viable solution has of course already been posted. 当然已经发布了一个可行的解决方案 。 But then, where's the fun in jumping right to the fix? 但是,那么跳到修复的乐趣在哪里?
(copypasta'd at OP's request) (根据OP的要求进行copypasta)
Because it is adding value +NULL before summing 因为它在求和之前加上值+ NULL
Try sum(column1) + sum(column2) 尝试sum(column1)+ sum(column2)
使用ISNULL函数获得所需的行为:
SELECT SUM(ISNULL(Column1, 0) + ISNULL(Column2, 0)) FROM [myTable]
Its a problem with a Null value. 这是一个Null值的问题。
SELECT SUM(IsNull(Column1, 0) + IsNull(Column2, 0) ) FROM [myTable]
to ensure it is always 0 at minimum. 确保它始终为0。
Thank you 谢谢
That's reason why your result is 9. ISNULL(expression, replacement_value) can help you in this situation. 这就是为什么你的结果是9. ISNULL(表达式,replacement_value)可以帮助你在这种情况下。 :) :)
An alternative explanation (just in case it works better for someone): 另一种解释(以防万一它对某人更好):
NULLs affect +
but do not affect SUM()
: where a NULL is +
-ed, it evaluates to NULL, where it is SUMmed, it is ignored. NULL影响+
但不影响SUM()
:其中NULL为+
-ed,它的计算结果为NULL,它是SUMmed,它被忽略。 (But SUM()
can return NULL when not a single argument was a value .) (但是当没有一个参数是值时, SUM()
可以返回NULL。)
So, there is only one row in your data sample (the last one) that produces a non-NULL result for the +
, and that result is 9
, which is what SUM()
returns as well. 因此,数据样本中只有一行(最后一行)为+
生成非NULL结果,结果为9
,这也是SUM()
返回的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.