Mysql - 计算同一字段的不同值

时间:2014-08-09 12:03:19

标签: mysql database

我有下表:

Table games
+----+----------+------+---------------------+
| id | name     | win  | date                |
+----+----------+------+---------------------+
|  1 | Fulano   | Y    | 2014-01-01 00:00:00 |
|  2 | Fulano   | Y    | 2014-01-01 00:00:00 |
|  3 | Fulano   | Y    | 2014-01-02 00:00:00 |
|  4 | Fulano   | Y    | 2014-01-03 00:00:00 |
|  5 | Fulano   | N    | 2014-01-03 00:00:00 |
|  6 | Beltrano | N    | 2014-01-01 00:00:00 |
|  7 | Beltrano | N    | 2014-01-01 00:00:00 |
|  8 | Beltrano | N    | 2014-01-02 00:00:00 |
|  9 | Beltrano | Y    | 2014-01-03 00:00:00 |
| 10 | Cicrano  | Y    | 2014-01-03 00:00:00 |
| 11 | Cicrano  | N    | 2014-01-03 00:00:00 |
+----+----------+------+---------------------+

我想做点什么:

SELECT name,count(win ='Y')AS wins,count(win ='N')AS loss FROM games GROUP BY name;

显然,由于“count”无法识别我发明的命令,我收到了不需要的回复:

+----------+----------+----------+
| name     | wins     | losses   |
+----------+----------+----------+
| Beltrano |        4 |        4 |
| Cicrano  |        2 |        2 |
| Fulano   |        5 |        5 |
+----------+----------+----------+

有人可以帮忙得到正确答案吗?

1 个答案:

答案 0 :(得分:4)

SELECT
    name,
    SUM( win = 'Y' ) AS wins,
    SUM( win = 'N' ) AS losses
FROM games
GROUP BY name;