获取Mysql group by并以不同的格式计算结果

时间:2014-11-05 15:38:45

标签: mysql

我需要获取每个状态的计数。所以我使用group by status列并得到以下结果

+------------------+
|  Status  | count |
+------------------+
|  created |   2   | 
+------------------+
| verified |   1   | 
+------------------+

我想知道我是否可以将结果作为

输入
+ ------------------+
| created | verified| 
+-------------------+
| 2       |   1     |
+-------------------+

1 个答案:

答案 0 :(得分:2)

在MySQL中你可以做到

SELECT sum(status = 'created') as created,
       sum(status = 'verified') as verified
FROM your_table

对于所有其他数据库引擎,请使用

SELECT sum(case when status = 'created' then 1 else 0 end) as created,
       sum(case when status = 'verified' then 1 else 0 end) as verified
FROM your_table