1

让您了解我正在尝试做的事情。简化的表结构将是:

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 子句。

谢谢。

4

2 回答 2

2

您可以使用 case 语句来做到这一点:

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
于 2013-03-13T15:11:58.067 回答
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
于 2013-03-13T15:09:16.007 回答