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

萝らか妹 提交于 2019-11-27 17:20:20

问题


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?


回答1:


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))



回答2:


, ( 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]


来源:https://stackoverflow.com/questions/4751772/tsql-average-of-all-values-in-a-column-that-are-not-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!