Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql AVG to ignore zero

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?

like image 631
Oranges13 Avatar asked Mar 17 '11 15:03

Oranges13


People also ask

Does SQL Avg ignore null?

SQL Average function and NULL valuesAVG() function does not consider the NULL values during its calculation.

How AVG function works in MySQL?

MySQL AVG function is used to find out the average of a field in various records. You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person.

Does Avg ignore null values Postgres?

Example #2: How Does the AVG() Function Deal With NULL Values in Postgres? The output shows that the AVG() ignores the NULL values.


3 Answers

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
like image 76
Martin Smith Avatar answered Nov 08 '22 20:11

Martin Smith


You could probably control that via the WHERE clause:

select avg( field ) from table where field > 0
like image 22
Mark Wilkins Avatar answered Nov 08 '22 18:11

Mark Wilkins


select avg(your_column) 
from your_table 
where your_column != 0
like image 25
Ike Walker Avatar answered Nov 08 '22 19:11

Ike Walker