让您了解我正在尝试做什么。简化的表结构将是:
homeTeamName | awayTeamName | homeTeamGoals | awayTeamGoals
-----------------------------------------------------------
Team1 | Team2 | 4 | 3
Team1 | Team3 | 0 | 1
Team3 | Team2 | 0 | 0
数据来自足球比赛。我想要做的是检索'形式'团队,即赢得了大多数游戏的团队(假设上表中填充了更多数据)。如果我想要检索特定团队的“胜利计数”,那么查询就相当容易了,如下所示。
SELECT COUNT(*) as winCount FROM matches_new
WHERE (
homeTeamName = 'Team1' AND
homeTeamGoals > awayTeamGoals
) OR (
awayTeamName = 'Team1' AND
awayTeamGoals > homeTeamGoals
)
ORDER BY winCount DESC LIMIT 1
该查询将返回特定团队可能拥有的“胜利”数量。现在我想做的是我的查询检查所有球队然后返回拥有最多“胜利”的球队的名称以及“胜利”(胜利数)的数量。
我真的不知道怎么做!我已经尝试了很多搜索,但很难想到如何描述这种类型的任务,或者想到任何类似的任务。我的麻烦似乎源于这样一个事实:我不知道你怎么做WHERE子句而不具体说明值应该等于什么。
感谢。
答案 0 :(得分:2)
您可以使用案例陈述:
select winningTeam, count(*) as winCount from (
select case
when homeTeamGoals > awayTeamGoals then homeTeamName
when awayTeamGoals > homeTeamGoals then awayTeamName
else null
end as winningTeam
from matches_new
) winners
where winningTeam is not null
group by winningTeam
order by winCount desc limit 1
或者你可以用工会来解决它:
SELECT teamName, COUNT(*) as winCount from (
select homeTeamName as teamName from matches_new
WHERE homeTeamGoals > awayTeamGoals
union all
select awayTeamName as teamName from matches_new
WHERE awayTeamGoals > homeTeamGoals
) as allWinners
GROUP BY teamName
ORDER BY winCount DESC LIMIT 1
答案 1 :(得分:0)
试试这个
select teamname, count(*) winCount from
(
select case when homeTeamGoals > awayTeamGoals then hometeamname
when wayTeamGoals > homeTeamGoals then awayTeamName end Teamname
from matches_new
where (homeTeamGoals > awayTeamGoals or wayTeamGoals > homeTeamGoals)
)
group by teamname
ORDER BY winCount DESC LIMIT 1