我试图通过在 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包含什么:
我查询的实际结果:
专栏r2
我希望查询的结果是: avg(3 + null, null + 6) = avg(3, 6) = 4.5
:
最佳答案
您可以将它们过滤掉,而不是将 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
上的浮点。
关于sql - SQL Server/Azure 中空值 "not working"的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71778854/