如何在sql中转换列中的行

时间:2017-03-24 15:09:07

标签: mysql sql db2

我有表员工

+------+-----------+
| name | is_active |
+------+-----------+
|  a   |         0 |
|  b   |         1 |
|  c   |         1 |
|  d   |         1 |
|  e   |         0 |
+------+-----------+

当我们使用查询

select   is_active, count(*) count 
from     employee 
group by is_active;

然后以

的形式输出
+-----------+--------+
| is_active |  count |
+-----------+--------+
|         1 |      3 |
|         0 |      2 |
+-----------+--------+

但我想以那种形式输出

+-----------+---+----+
| is_active | 0 |  1 |
+-----------+---+----+
| count     | 2 |  3 |
+-----------+---+----+

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

int

在MySQL中,您可以使用select 'count' as is_active, count(case when is_active = 0 then 1 end) as count_0, count(case when is_active = 1 then 1 end) as count_1 from t;

来编写
sum