SQL:带有 NULL 值的 AVG
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22220449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL: AVG with NULL Values
提问by user3364656
as far as i understood the AVG() function ignores NULL Values.
据我了解 AVG() 函数忽略 NULL 值。
So AVG(4,4,4,4,4,NULL) --> 4
所以 AVG(4,4,4,4,4,NULL) --> 4
In my case i don′t want this to happen.
就我而言,我不希望这种情况发生。
I need a solution like that: AVG(4,4,4,4,4,NULL) --> 3,33
我需要这样的解决方案: AVG(4,4,4,4,4,NULL) --> 3,33
without replacing the NULL values directly in the table itself. Is there any way to do this?
无需直接替换表本身中的 NULL 值。有没有办法做到这一点?
回答by Bohemian
Use coalesce()
to return the real value of zero for null columns:
使用coalesce()
为空列返回零的真正价值:
select avg(coalesce(some_column, 0))
from ...
回答by user2864740
You are correct about the behavior of AVG - use COALESCEto convert the NULLs to 0 in the aggregate.
您对 AVG 的行为是正确的 - 使用COALESCE在聚合中将 NULL 转换为 0。
See this answerin "Why SUM(null) is not 0 in Oracle?"
请参阅“为什么 SUM(null) 在 Oracle 中不是 0?”中的答案。
If you are looking for a rationale for this behaviour, then it is to be found in the ANSI SQL standards which dictate that aggregate operators ignore NULL values.
如果您正在寻找这种行为的基本原理,那么可以在 ANSI SQL 标准中找到它,该标准规定聚合运算符忽略 NULL 值。
The relevant code is then, simply:
相关的代码就是:
Avg(Coalesce(col,0))
回答by Mohammed Salman Shaikh
You can use coalesce
or nvl
also.
Since coalesce
examples are already given above, here is an example of nvl
您可以使用coalesce
或nvl
也。由于coalesce
上面已经给出了例子,这里是一个例子nvl
Avg(Nvl(Column_Name),0)
Coalesce, Nvl, Nvl2 functions are handy in such cases of handling null values. You should look up some examples and documentation on these.
Coalesce、Nvl、Nvl2 函数在处理空值的情况下非常方便。您应该查找一些关于这些的示例和文档。
回答by NatiCog
NVL, NVL2, or COALESCE could be used to solve this issue.
NVL、NVL2 或 COALESCE 可用于解决此问题。
like this select avg(4,4,4,4, nvl(null, 0 )) from dual;
像这样 select avg(4,4,4,4, nvl(null, 0 )) from dual;