单个分组值的多个计数

时间:2013-10-19 14:01:19

标签: mysql

我有一张桌子记录了比赛中球员得分(例如表1)。我正在尝试编写一个查询,该查询将计算每个玩家获得每个分数的次数(例如结果1)。我可以轻松地为其中一个点值执行此操作: -

SELECT name, COUNT(*) AS 10s FROM points WHERE points = '10' GROUP BY name

但无法确定如何包含所有三个点值。是否可能,如果有的话,有人可以帮助我吗?

非常感谢

Table 1
+---------+-----+
| name | points |
| John | 10     |
| Pete | 5      |
| Anna | 10     |
| John | 10     |
| Pete | 0      |
| Anna | 5      |
| John | 5      |
| Pete | 5      |
| Anna | 0      |
+---------+-----+

Results 1
+------+-----+----+-----+
| name | 10s | 5s |  0s |
| John | 2   | 1  |  0  |
| Pete | 0   | 2  |  1  |
| Anna | 1   | 1  |  1  |
+------+-----+----+-----+

1 个答案:

答案 0 :(得分:2)

您可以使用sum()添加条件true

的位置
SELECT name, 
       sum(points = 10) AS 10s,
       sum(points = 5) AS 5s,
       sum(points = 0) AS 0s
FROM points 
GROUP BY name