我有一个列可以获得0值,但我需要计算该列的平均值,而不将这些0作为分隔符的一部分计算。
我有以下查询:
SELECT AVG(CAST(RATING AS NUMERIC(18, 2))) AS AVERAGE,
QUESTIONID,
Questions.SHORTVERSION,
COUNT(CASE
WHEN RATING > 0
THEN 1
ELSE NULL
END) AS COUNT
FROM AnswersRating
INNER JOIN Questions ON Questions.ID = QUESTIONID
WHERE SURVEYID IN
(
SELECT ID
FROM SURVEYS
WHERE FLIGHTDATAID = '8371'
)
GROUP BY QUESTIONID,
Questions.SHORTVERSION
ORDER BY QUESTIONID;
我在某处读到我可以使用NULLIF
来帮助解决这个问题,但我无法弄清楚如何正确使用它。谁可以帮助我?
答案 0 :(得分:4)
您可以使用NULLIF将0转换为NULL,因为AVG将忽略NULL:
NULLIF(RATING, 0)