转结果表mysql

时间:2014-03-08 09:36:02

标签: mysql sql group-by

我在Mysql数据库中有一个架构:

CREATE TABLE test
(
ID int,
Country varchar(50),
category varchar(10)
); 

INSERT INTO test VALUES (1,'USA','A');
INSERT INTO test VALUES (2,'USA','A');
INSERT INTO test VALUES (3,'USA','B');
INSERT INTO test VALUES (4,'Canada','A');

使用此查询:

SELECT country,count(category),category FROM test GROUP BY country,category;

我得到了这个结果:

+---------+-------+----------+
| Country | count | category |
+---------+-------+----------+
| Canada  |     1 | A        |
| USA     |     2 | A        |
| USA     |     1 | B        |
+---------+-------+----------+

但我希望得到这样的结果:

+---------+---+---+
| Country | A | B |
+---------+---+---+
| Canada  | 1 | 0 |
| USA     | 2 | 1 |
+---------+---+---+

任何建议都会很好。感谢

这是我的SQL Fiddle

1 个答案:

答案 0 :(得分:2)

SELECT country, 
       sum(case when category = 'A' then 1 else 0 end) as A,
       sum(case when category = 'B' then 1 else 0 end) as B
FROM test 
GROUP BY country;

SQLFiddle demo