Average and Case in SQL

佐手、 提交于 2019-12-20 05:59:13

问题


I am trying to generate a report and the following code does not produce the desired results which gives me 2 lines rather than one.

The ScoreTypeID could have values of 22, 52, 3 or 4 . if it is 22 or 52, I need the average and if not I need to show 0. Any idea what may be the problem ? Thanks.

  CASE WHEN FAS1.ScoreTypeID = 22 THEN avg(fas1.totalscore)  
       WHEN FAS1.ScoreTypeID = 52 THEN avg(fas1.totalscore)   ELSE 0    
  END  AS   'Total Score',   

回答1:


I think in your full query, you are missing the GROUP BY clause, eg

SELECT ...
FROM   ....
WHERE   ..
GROUP BY FAS1.ScoreTypeID



回答2:


I think this is what you want:

 coalesce(avg(CASE WHEN FAS1.ScoreTypeID in (22, 52) THEN fas1.totalscore end), 0) AS   'Total Score'

This takes the average when the score is 22 or 52. If there are no values present, it returns NULL. The coalesce turns the NULL into a 0.




回答3:


To keep it in the format you have chosen you could use:

CASE WHEN FAS1.ScoreTypeID IN (22,52) THEN avg(fas1.totalscore) ELSE 0
  END  AS   'Total Score', 


来源:https://stackoverflow.com/questions/13935413/average-and-case-in-sql

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