Reinaldo
Reinaldo

Reputation: 7

Mysql - Counting different values of the same field

I have the following table:

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 |
+----+----------+------+---------------------+

I would like to do something like:

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

Obviously I get an unwanted response due to the "count" does not recognize the command that I invented:

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

Could someone help get the correct answer?

Upvotes: 1

Views: 45

Answers (1)

hjpotter92
hjpotter92

Reputation: 80657

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

Upvotes: 4

Related Questions