SQL 服务器/Azure 中的空值总和 "not working"

Sum with nulls "not working" in SQL Server / Azure

我试图通过在 AVG() 函数中使用 case 语句来计算一组列的平均值并从分母中排除零行。我读到 avg() 排除了 NULL 结果,所以我使用 case 语句将 0 替换为 NULL。然而,这不是我在实践中发现的 - 请参阅下面的代码。有人可以解释为什么会这样吗?如果您可以建议进行代码调整以实现我所追求的目标,那也很棒。谢谢。

with a as
(
select 0 t1, 3 t2 
)
, b as
(
select 6 t1, 0 t2
)
, c as -- building a small table containing test data.
(
select * from a
union all
select * from b
)
select sum(case when t2 = 0 then null else t2 end + case when t1 = 0 then null else t1 end) r1 
  , avg(case when t2 = 0 then null else t2 end + case when t1 = 0 then null else t1 end) r2
  , avg(t1) r3
from c

子查询c包含什么:

t1 t2
0 3
6 0

我查询的实际结果:

r1 r2 r3
NULL NULL 3

r2 是我希望的查询结果:avg(3 + null, null + 6) = avg(3, 6) = 4.5:

r1 r2 r3
9 4.5 3

而不是将 0 值设置为 null,您可以将它们过滤掉介于两者之间的某个位置:

with a as
(
select cast(0 as float) t1, cast(3 as float) t2 
)
, b as
(
select cast(6 as float) t1, cast(0 as float) t2
)
, c as -- building a small table containing test data.
(
select * from a where t1 > 0 or t2 > 0
union all
select * from b where t1 > 0 or t2 > 0
)
select sum(t2+t1) r1 
  , avg(t2+t1) r2
  , avg(t1) r3
from c;

输出:

| r1 | r2 | r3 |
|----+----+----|
| 9  | 4.5| 3  |

*查看我如何将数字转换为 float 类型,以便捕获 r2 上的浮点数。