MySQL:使用空值求平均值

Zom*_*ies 8 mysql sql

有没有一种简单的方法可以排除空值影响平均值?它们似乎算作0,这不是我想要的.我只是不希望把他们的平均考虑,但这里是抓,我不能从结果集中删除它们,因为该记录上有数据,我确实需要.

更新:

例:

select avg(col1+col2), count(col3) from table1
where
group by SomeArbitraryCol
having avg(col1+col2) < 500 and count(col3) > 3
order by avgcol1+col2) asc;
Run Code Online (Sandbox Code Playgroud)

这对我有用,但是平均值不准确,因为它们将空值计为0,这实际上是在抛弃整个平均值.

Cad*_*oux 15

SQL中的聚合函数(SUM,AVG,COUNT等)始终自动排除NULL.

所以SUM(col)/ COUNT(col)= AVG(col) - 这很棒且一致.

COUNT(*)的特殊情况计算每一行.

如果组成一个带NULL的表达式:A + B,其中A或B为NULL,则A + B将为NULL,而不管其他列是否为NULL.

当存在NULL时,通常AVG(A + B)<> AVG(A)+ AVG(B),它们也可能具有不同的分母.您必须包装列:AVG(COALESCE(A,0)+ COALESCE(B,0))来解决这个问题,但也可能排除COALESCE(A,0)+ COALESCE(B,0)的情况.

根据您的代码,我建议:

select avg(coalesce(col1, 0) + coalesce(col2, 0)), count(col3) from table1
where coalesce(col1, col2) is not null -- double nulls are eliminated
group by SomeArbitraryCol
having avg(coalesce(col1, 0) + coalesce(col2, 0)) < 500 and count(col3) > 3
order by avg(coalesce(col1, 0) + coalesce(col2, 0)) asc;
Run Code Online (Sandbox Code Playgroud)


Jac*_*lor 7

AVG(number) 
Run Code Online (Sandbox Code Playgroud)

这是我能想到的最佳方式.这应该自动不包括空值.是一个小小的阅读.