CASE WHEN字段的平均值

时间:2019-03-06 21:32:27

标签: sql sql-server tsql

如何获取TotalTeamMembership列的平均值?

SELECT Player,
CASE WHEN Basketball = '' THEN 0 ELSE 1 END + 
CASE WHEN Baseball = '' THEN 0 ELSE 1 END + 
CASE WHEN Football = '' THEN 0 ELSE 1 END AS TotalTeamMembership
FROM PlayerMembership;

这是我目前得到的:

Progress

这就是我需要的:

Goal

谢谢您的指导!

2 个答案:

答案 0 :(得分:3)

您可以使用AVG()

SELECT AVG(CASE WHEN Basketball = '' THEN 0.0 ELSE 1 END + 
           CASE WHEN Baseball = '' THEN 0 ELSE 1 END + 
           CASE WHEN Football = '' THEN 0 ELSE 1 END
           ) AS avg_TotalTeamMembership
FROM PlayerMembership;

答案 1 :(得分:1)

您可以使用AVG聚合函数:

SELECT AVG(TotalTeamMembership)
FROM (SELECT Player,
       CASE WHEN Basketball = '' THEN 0 ELSE 1 END + 
       CASE WHEN Baseball = '' THEN 0 ELSE 1 END + 
       CASE WHEN Football = '' THEN 0 ELSE 1 END AS TotalTeamMembership
      FROM PlayerMembership) s;