MySQL获取值在列中出现的次数?
在MySQL中,我有一个表,其中包含一轮比赛的结果。此表的结果列包含值“赢得”、“丢失”或“绘制”。我如何按竞争对手分组并获得特定值的计数?这样做的目的是能够根据赢家和输家的数量对竞争对手进行排序,并在数据库查询中计算得分 所以,我的桌子是:MySQL获取值在列中出现的次数?,mysql,Mysql,在MySQL中,我有一个表,其中包含一轮比赛的结果。此表的结果列包含值“赢得”、“丢失”或“绘制”。我如何按竞争对手分组并获得特定值的计数?这样做的目的是能够根据赢家和输家的数量对竞争对手进行排序,并在数据库查询中计算得分 所以,我的桌子是: +--------------+---------+--------+ | CompetitorId | MatchId | Result | +--------------+---------+--------+ | 1 | 1
+--------------+---------+--------+
| CompetitorId | MatchId | Result |
+--------------+---------+--------+
| 1 | 1 | won |
| 2 | 1 | lost |
| 1 | 2 | won |
| 3 | 2 | lost |
+--------------+---------+--------+
我试图得到的结果是:
+--------------+------+--------+
| CompetitorId | Wins | Losses |
+--------------+------+--------+
| 1 | 2 | 0 |
| 2 | 0 | 1 |
| 3 | 0 | 1 |
+--------------+------+--------+
我尝试的查询是:
SELECT CompetitorId, COUNT(result='won') AS wins, COUNT(result='lost') AS losses
FROM match_competitors
GROUP BY CompetitorId
可以使用包含大小写的sum,当列为所需列时,其值为1,当列不为所需列时,其值为0:
SELECT CompetitorId, sum(case result
when 'won' then 1
else 0
end) as wins,
sum(case result
when 'lost' then 1
else 0
end) as losses
FROM match_competitors
GROUP BY CompetitorId
非常感谢。我看到了太多可怕的选择,加入我可以总结,等等。。。非常感谢。我总是忘记案件陈述。耐心地等待接受计时器的滴答声。。。