Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get AVG ignoring Null or Zero values

How can I get the AVG of a column ignoring NULL and zero values?

I have three columns to get their average, I try to use the following script:

SELECT distinct      AVG(cast(ISNULL(a.SecurityW,0) as bigint)) as Average1      ,AVG(cast(ISNULL(a.TransferW,0) as bigint)) as Average2      ,AVG(cast(ISNULL(a.StaffW,0) as bigint)) as Average3 FROM Table1 a,  Table2 b WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL AND a.TransferW<> 0 AND a.TransferWIS NOT NULL AND a.StaffW<> 0 AND a.StaffWIS NOT NULL AND MONTH(a.ActualTime) = 4 AND YEAR(a.ActualTime) = 2013 

I don't get any results, however the three columns have values including NULL and zeros!

Is there anyway to exclude null values before getting the average?

example: AVERAGE(NOTNULL(SecurityW))

like image 615
SVI Avatar asked Jul 02 '13 11:07

SVI


People also ask

Does Avg ignore NULL values?

AVG() function does not consider the NULL values during its calculation.

Does SQL AVG ignore 0?

To exclude entries with “0”, you need to use NULLIF() with function AVG().

Is NULL counted in AVG?

By default, the AVG function uses ALL clause whether you specify it or not. It means the AVG function will take all non-NULL values when it calculates the average value.

Does Avg ignore NULL values Postgres?

PostgreSQL AVG() function and NULL Third, use the AVG() function to calculate average values in the amount column. It returns 20, meaning that the AVG() function ignores NULL values.


2 Answers

NULL is already ignored so you can use NULLIF to turn 0 to NULL. Also you don't need DISTINCT and your WHERE on ActualTime is not sargable.

SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,        AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,        AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT))    AS Average3 FROM   Table1 a WHERE  a.ActualTime >= '20130401'        AND a.ActualTime < '20130501'  

PS I have no idea what Table2 b is in the original query for as there is no join condition for it so have omitted it from my answer.

like image 153
Martin Smith Avatar answered Sep 30 '22 20:09

Martin Smith


this should work, haven't tried though. this will exclude zero. NULL is excluded by default

AVG (CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END) 
like image 28
chetan Avatar answered Sep 30 '22 19:09

chetan