带连接的SQL Select并计算百分比

时间:2020-08-18 05:01:36

标签: sql join select group-by

我有三个表,我正在尝试做出一条选择语句,以使我得到类似于以下结果的结果 队伍:

ID   Name
1     A
2     B
3     C

玩家:

ID   Name  TeamID
1    P1     1
2    P2     1
3    P3     2

目标:(目标类型:H代表家,A代表客场,T代表训练)

ID   PID  goaltype
1    1     A
2    1     A
3    1     H
4    2     A
5    2     H
6    3     A
7    3     T

结果将类似于:

Team    totalGoals  home    away    trainig      percentage[(home/total)*100]
A       5            2        3        0             40%  
B       2            0        1        1              0
C       0            0        0        0              0

这是我当前的查询:

select t.name, 
  count(g.id) as totalGoals, 
  sum(case when g.GTYPE = 'H' then 1 else 0 end) as home, 
  sum(case when g.GTYPE = 'A' then 1 else 0 end) as away, 
  sum(case when g.GTYPE = 'T' then 1 else 0 end) as training,
  --(home/totalGoals) as percentage 
from teams t 
left join players p on p.TeamID = t.id 
left join goals g on g.pid = p.id 
group by t.name

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合来获得所需的结果:

SELECT t.Name AS Team,
       COUNT(g.goaltype) AS totalGoals,
       SUM(CASE WHEN g.goaltype = 'H' THEN 1 ELSE 0 END) AS home,
       SUM(CASE WHEN g.goaltype = 'A' THEN 1 ELSE 0 END) AS away,
       SUM(CASE WHEN g.goaltype = 'T' THEN 1 ELSE 0 END) AS training,
       CASE WHEN COUNT(g.goaltype) = 0 THEN 0
            ELSE 100.0 * SUM(CASE WHEN g.goaltype = 'H' THEN 1 ELSE 0 END) /
                 COUNT(g.goaltype)
       END AS percentage
FROM Teams t
LEFT JOIN Players p ON p.TeamID = t.ID
LEFT JOIN Goals g ON g.PID = p.ID
GROUP BY t.Name
ORDER BY t.Name

输出:

team    totalgoals  home    away    training    percentage
A       5           2       3       0           40
B       2           0       1       1           0
C       0           0       0       0           0

Demo on SQLFiddle