I have a number mysql database field named “numbers” in which there are 10 entries with numbers ranging from 0-10.
I would like to find the average of this, but excluding all the entries where number = 0.
But I would also like to count how many entries there are – including the ones where number = 0.
So I can’t just add a WHERE numbers!=0, as that’d give a wrong result in my COUNT.
So I need somthing like.
AVG(if(numbers!=0)) AS average
How about this?
Notice how this method doesn’t force you to use a
whereclause, in case you want to use this as part of a larger query where you don’t want to exclude zero values in general.Also, by the way,
avgskipsnullvalues, so in the above example we usednullifto turn0values intonullvalues. If you usenullvalues to represent values that shouldn’t be taken into account for the average (for example, if0is a legitimate value), then just useavg(field).