Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Average of all values in a column that are not zero

Tags:

tsql

average

I'm in the process of writing a report and am looking to get the average value of an age column. The problem is that not all rows have an age.

If the values for the column are 0 2 4 I would want 3 returned, not 2. I can not simply exclude the zero rows with a WHERE as I'm using using other columns in those rows. Is there such a thing as a AvgIfNotZero type of function?

like image 608
Justin808 Avatar asked Jan 20 '11 19:01

Justin808


People also ask

How do you find the average without zeros in SQL?

One approach is AVG() and CASE / NULLIF() : SELECT AVG(NULLIF(Column1, 0)) as Average FROM table1; Average ignores NULL values.

Does SQL AVG ignore 0?

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

How do you average all values in a column in SQL?

The avg() function has the following syntax: SELECT AVG( column_name ) FROM table_name; The avg() function can be used with the SELECT query for retrieving data from a table.

Can we use AVG function in where clause?

This query throws an error, because you cannot use AVG() in a WHERE condition. Since AVG() is a group function, you can only use it in a SELECT statement or in a HAVING clause. The query inside a main query is called a subquery.


2 Answers

SELECT

    AVG (CASE WHEN Value <> 0 THEN Value ELSE NULL END)
    ....

AVG won't take into account NULL values. Or this

    AVG (NULLIF(Value, 0))
like image 141
gbn Avatar answered Oct 03 '22 07:10

gbn


, ( SELECT AVG(a) FROM

        (
        SELECT NULLIF([Column1], 0)
            UNION ALL
        SELECT  NULLIF([Column2], 0)
            UNION ALL
        SELECT  NULLIF([Column3], 0)
            UNION ALL
        SELECT  NULLIF([Column4], 0)
        ) T (a)
    ) AS [4 Column Average]
like image 36
Milo Woodward Avatar answered Oct 03 '22 08:10

Milo Woodward