SQL: AVG with NULL Values

馋奶兔 提交于 2019-12-19 07:29:08

问题


as far as i understood the AVG() function ignores NULL Values.

So 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

without replacing the NULL values directly in the table itself. Is there any way to do this?


回答1:


Use coalesce() to return the real value of zero for null columns:

select avg(coalesce(some_column, 0))
from ...



回答2:


You are correct about the behavior of AVG - use COALESCE to convert the NULLs to 0 in the aggregate.

See this answer in "Why SUM(null) is not 0 in Oracle?"

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.

The relevant code is then, simply:

Avg(Coalesce(col,0))



回答3:


You can use coalesce or nvl also. Since coalesce examples are already given above, here is an example of 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.




回答4:


NVL, NVL2, or COALESCE could be used to solve this issue.

like this select avg(4,4,4,4, nvl(null, 0 )) from dual;



来源:https://stackoverflow.com/questions/22220449/sql-avg-with-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!