问题
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