22

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?

Oranges13
  • 1,084
  • 1
  • 10
  • 33

4 Answers4

99

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
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
5

You could probably control that via the WHERE clause:

select avg( field ) from table where field > 0
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
  • Only if the rows where field is greater than zero are the ones I'm worried about. Unfortunately in this case, there are 3 other columns I need to check where that may not be the case. – Oranges13 Mar 17 '11 at 19:53
1
select avg(your_column) 
from your_table 
where your_column != 0
Ike Walker
  • 64,401
  • 14
  • 110
  • 109
0

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;
Thomas Berger
  • 1,860
  • 13
  • 26
Barvajz
  • 25
  • 1