带有空值的求和“不起作用”在 SQL Server/Azure 中
我试图通过在AVG()函数中使用案例语句来平均一组列,并将其从分母中排除为零。我读到AVG()不包括无效结果,因此正在使用案例语句用null替换0。但是,这不是我在实践中发现的 - 请参见下面的代码。有人可以解释为什么会发生这种情况吗?如果您可以提出一项代码调整以实现我之后的目标,那也将是晶圆厂。谢谢。
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 | 3 | 列 |
R2
是我希望我的查询结果为:avg (3 + NULL,NULL + 6)= AVG(3,6)= 4.5
:
R1 | R2 | R3 |
---|---|---|
9 | 4.5 | 3 |
I'm trying to average a set of columns and exclude rows with zero from the denominator by using a case statement within an AVG() function. I read that avg() excludes NULL results so am using the case statement to replace 0's with NULL's. However that's not what I find in practice - see code below. Can someone explain why this happens? If you can suggest a code tweak to achieve what I'm after that would also be fab. Thanks.
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
What subquery c contains:
t1 | t2 |
---|---|
0 | 3 |
6 | 0 |
The actual result of my query:
r1 | r2 | r3 |
---|---|---|
NULL | NULL | 3 |
Column r2
is what I would like the result of my query to be: avg(3 + null, null + 6) = avg(3, 6) = 4.5
:
r1 | r2 | r3 |
---|---|---|
9 | 4.5 | 3 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将它们过滤掉,而不是将 0 值设置为
null
:输出:
*了解如何将数字转换为
float
类型,以便捕获 r2 上的浮点。Instead of setting the 0 values to
null
, you can filter them out somewhere in between:Output:
*See how I convert numbers to
float
type, in order to capture the floating point onr2
.