Mysql AVG to ignore zero

2019-03-11 02:15发布

I need to perform an avg on a column, but I know that most of the values in that column will be zero. Out of all possible rows, only two will probably have positive values. How can I tell mySQL to ignore the zeros and only average the actual values?

4条回答
够拽才男人
2楼-- · 2019-03-11 02:26

Assuming that you might want to not totally exclude such rows (perhaps they have values in other columns you want to aggregate)

SELECT AVG(NULLIF(field ,0)) 
from table
查看更多
狗以群分
3楼-- · 2019-03-11 02:40

You could probably control that via the WHERE clause:

select avg( field ) from table where field > 0
查看更多
太酷不给撩
4楼-- · 2019-03-11 02:40

You can convert zeros to NULL, then AVG() function will work only with not NULL values.

UPDATE table SET column = NULL WHERE column='0';
SELECT AVG(column) FROM table;
查看更多
爷、活的狠高调
5楼-- · 2019-03-11 02:48
select avg(your_column) 
from your_table 
where your_column != 0
查看更多
登录 后发表回答