DIVIDING时如何处理空值
How to deal with null values while DIVIDING
我有一个看似简单的问题,但我不知道如何处理。
我有两个按值或 null
填充的列。
我必须像这样对这些进行平均:
- 如果两者都是值 = (A+B)/2
- 如果一个为空则 = A 或 B。
是否可以用不同的方式来写:
case when a is not null and b is not null then....
etc.
如果我使用简单的 (a+b)/2
,在其中一个值为 null
.
的情况下,我会得到 null
可能最简单的方法是将 outer apply
与 avg()
一起使用,因为 avg()
会忽略 NULL
值:
select v.avg_ab
from t outer apply
(select avg(x) as avg_ab
from (values (t.A), (t.B)
) v
) v;
您也可以使用复杂的 case
表达式来执行此操作:
select (case when A is not NULL and B is not NULL then (A + B) / 2
when A is not NULL then A
when B is not NULL then B
end) as avg_ab
. . .
这对 2 个值来说效果很好;它对于 3 是可行的。除此之外它并没有很好地概括。另一种使用 case
的方法更具通用性:
select ( (coalesce(A, 0) + coalesce(B, 0)) /
((case when A is not null then 1 else 0 end) +
(case when B is not null then 1 else 0 end)
)
)
不过apply
方法还是比较简单
假设它们都是 null
的情况应该导致 null
平均值,您可以使用 (A+A)/2=A
的数学 "trick" 并使用 coalesce
以优雅的方式写这篇文章,恕我直言:
(COALESCE(a, b) + COALESCE(b, a)) / 2
尝试以下操作:
SELECT (ISNULL(a, b)+ISNULL(b, a))/2
这将是最干净的解决方案
select coalesce((A+B)/2,A,B)
.
.
.
演示:
declare @t table (id int,A int,B int)
insert into @t values (1,30,50),(2,30,null),(3,null,50),(4,null,null)
select id,A,B,coalesce((A+B)/2,A,B) as result
from @t
+----+------+------+--------+
| id | A | B | result |
+----+------+------+--------+
| 1 | 30 | 50 | 40 |
+----+------+------+--------+
| 2 | 30 | NULL | 30 |
+----+------+------+--------+
| 3 | NULL | 50 | 50 |
+----+------+------+--------+
| 4 | NULL | NULL | NULL |
+----+------+------+--------+
我有一个看似简单的问题,但我不知道如何处理。
我有两个按值或 null
填充的列。
我必须像这样对这些进行平均:
- 如果两者都是值 = (A+B)/2
- 如果一个为空则 = A 或 B。
是否可以用不同的方式来写:
case when a is not null and b is not null then....
etc.
如果我使用简单的 (a+b)/2
,在其中一个值为 null
.
null
可能最简单的方法是将 outer apply
与 avg()
一起使用,因为 avg()
会忽略 NULL
值:
select v.avg_ab
from t outer apply
(select avg(x) as avg_ab
from (values (t.A), (t.B)
) v
) v;
您也可以使用复杂的 case
表达式来执行此操作:
select (case when A is not NULL and B is not NULL then (A + B) / 2
when A is not NULL then A
when B is not NULL then B
end) as avg_ab
. . .
这对 2 个值来说效果很好;它对于 3 是可行的。除此之外它并没有很好地概括。另一种使用 case
的方法更具通用性:
select ( (coalesce(A, 0) + coalesce(B, 0)) /
((case when A is not null then 1 else 0 end) +
(case when B is not null then 1 else 0 end)
)
)
不过apply
方法还是比较简单
假设它们都是 null
的情况应该导致 null
平均值,您可以使用 (A+A)/2=A
的数学 "trick" 并使用 coalesce
以优雅的方式写这篇文章,恕我直言:
(COALESCE(a, b) + COALESCE(b, a)) / 2
尝试以下操作:
SELECT (ISNULL(a, b)+ISNULL(b, a))/2
这将是最干净的解决方案
select coalesce((A+B)/2,A,B)
.
.
.
演示:
declare @t table (id int,A int,B int)
insert into @t values (1,30,50),(2,30,null),(3,null,50),(4,null,null)
select id,A,B,coalesce((A+B)/2,A,B) as result
from @t
+----+------+------+--------+
| id | A | B | result |
+----+------+------+--------+
| 1 | 30 | 50 | 40 |
+----+------+------+--------+
| 2 | 30 | NULL | 30 |
+----+------+------+--------+
| 3 | NULL | 50 | 50 |
+----+------+------+--------+
| 4 | NULL | NULL | NULL |
+----+------+------+--------+