我的查询有问题。我最近刚开始使用SQL。在下面的第一个表格中,我想计算获胜最多的球队数量,也包括获胜次数为零的球队。表格名称以红色突出显示。
我希望查询结果看起来像是我附加的第二张图片,还是这样
Phenix 2
StarWar 1
Strack 1
Serious 0
Apolo 0
APTX 0
Poki 0
到目前为止,我最好的查询是:
SELECT t1.Team_Name
, COUNT(winner) AS TotalWins
FROM result r
LEFT JOIN team_1 t1
ON r.Team1_ID = t1.Team1_ID
GROUP BY winner
UNION
SELECT t2.Team_Name
, COUNT(distinct winner) AS TotalWins
FROM result r
LEFT JOIN team_2 t2
ON r.Team2_ID = t2.Team2_ID
GROUP BY Winner
ORDER BY TotalWins DESC;
我得到的结果不包括零获胜的球队,它只会为所有球队加1。
答案 0 :(得分:1)
先将team
表合并,然后再加入结果表,然后可以使用sum()
函数来获取total wins
。
select t1.Team_Name, sum(case when coalesce(t2.battle_no, '') = '' then 0 else 1 end) as TotalWins
from (select Team_Name, team1_id as id from team_1
union all
select Team_Name, team1_id as id from team_1) t1
left join result t2 on t2.Team2_ID = t1.team1_id or t2.Team1_ID = t1.team1_id
答案 1 :(得分:0)
将左表从结果更改为两个团队的团队
SELECT t1.Team_Name, COUNT(winner) AS TotalWins
FROM team_1 t1 LEFT JOIN result r
ON r.Team1_ID = t1.Team1_ID
GROUP BY winner
UNION
SELECT t2.Team_Name, COUNT(distinct winner) AS TotalWins
FROM team_2 t2 LEFT JOIN result r
on r.Team2_ID = t2.Team2_ID
GROUP BY Winner
ORDER BY TotalWins DESC