Mysql AVG to ignore zero

Oranges13 picture Oranges13 · Mar 17, 2011 · Viewed 19.8k times · Source

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?

Answer

Martin Smith picture Martin Smith · Mar 17, 2011

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