[英]SQL: Sum of two columns containing NULLS?
I want to sum two columns to get the third column.我想将两列相加得到第三列。 If a row has NULL
for both columns, I want the third column to have NULL
, instead of a 0
.如果一行的两列都有NULL
,我希望第三列有NULL
,而不是0
。 The reason is because I want to get the average of the third column and having a 0
will change that average.原因是因为我想获得第三列的平均值,而0
会改变该平均值。
| Value1 | Value2 | Value3 |
|--------|--------|--------|
| 10 | NULL | 10 |
| 20 | NULL | 20 |
| NULL | NULL | NULL |
| 20 | 30 | 50 |
| NULL | NULL | NULL |
I have tried the following approaches, but they all give a 0
for NULL
rows.我尝试了以下方法,但它们都为NULL
行给出了0
。 What is the best way to achieve this?实现这一目标的最佳方法是什么?
CREATE TABLE #AMOUNTS (
Value1 INT,
Value2 INT
)
INSERT INTO #AMOUNTS VALUES
(10, NULL), (20, NULL), (NULL, NULL), (20, 30), (NULL, NULL)
SELECT
Value1, Value2
,ISNULL(Value1, 0) + ISNULL(Value2, 0) AS Value3
,COALESCE(Value1, 0) + COALESCE(Value2, 0) AS Value3
,CASE WHEN Value1 = NULL AND Value2 = NULL THEN NULL
ELSE ISNULL(Value1, 0) + ISNULL(Value2, 0)
END AS Value3
FROM #AMOUNTS
| Value1 | Value2 | Value3 | Value3 | Value3 |
|--------|--------|--------|--------|--------|
| 10 | NULL | 10 | 10 | 10 |
| 20 | NULL | 20 | 20 | 20 |
| NULL | NULL | 0 | 0 | 0 |
| 20 | 30 | 50 | 50 | 50 |
| NULL | NULL | 0 | 0 | 0 |
When testing for NULL use operator IS
not =
:测试 NULL 时使用运算符IS
not =
:
CASE WHEN Value1 IS NULL AND Value2 IS NULL THEN NULL
ELSE ISNULL(Value1, 0) + ISNULL(Value2, 0)
Use a case
expression:使用case
表达式:
select (case when value1 is null and value2 is null
then null
else coalesce(value1, 0) + coalesce(value2, 0)
end)
That said, apply
is a simple way to get the average:也就是说, apply
是一种获取平均值的简单方法:
select t.*, v.avg_value
from t cross apply
(select avg(v.val) as avg_value
from (values (value1), (value2)) v(val)
) v;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.