MySQL复杂计数问题

时间:2017-03-30 15:37:42

标签: mysql count

我正在尝试进行查询,如果足球队赢得主场比赛(例如利物浦足球俱乐部),那么将1添加到一个列中,并且同样的损失(这将是AwayWins,并且抽签将是'画')。

以下查询效果很好,它只是比较目标分数并在适当的位置添加1。

SELECT *,
    IF(max(`goalsHomeTeam`)>`awayTeamName`,'1','') as HomeWins,
    IF(max(`goalsHomeTeam`)<`awayTeamName`,'1','') as AwayWins,
    IF(max(`goalsHomeTeam`)=`awayTeamName`,'1','') as Draw
FROM fixtures 
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY fixtures_id
LIMIT 10

这看起来像:

enter image description here

但是,我真正想要展示的只是3个字段:

HomeWins,AwayWins和Draw

然后计算每个方框(例如根据HomeWins上方的图片:9,AwayWins:0和Draw:0。

我尝试添加一些简单的东西,例如在IF周围包裹一个计数但是没有用。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试此查询

SELECT 
    SUM(IF(`goalsHomeTeam` > `awayTeamName`,1,0)) AS HomeWins,
    SUM(IF(`goalsHomeTeam` < `awayTeamName`,1,0)) AS AwayWins,
    SUM(IF(`goalsHomeTeam` = `awayTeamName`,1,0)) AS Draw
FROM fixtures 
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY `homeTeamName`

答案 1 :(得分:0)

您可以这样做:

Select SUM(T1.HomeWins), SUM(T1.AwayWins), SUM(T1.Draw)
From (#your query here#) AS T1

简单的例子:http://rextester.com/SYQI26450