选择某些行的计数作为列

时间:2016-03-14 23:53:17

标签: mysql sql database

我有一张表"状态"接受TINYINT的列。例如:

name   | status
-------+--------
john   | 0
joe    | 1
johann | 0
jan    | 1
jane   | 0

如何计算谁是状态1以及谁是状态0?

status1 | status0
--------+--------
2       | 3

2 个答案:

答案 0 :(得分:1)

只需使用条件聚合:

select sum(status = 1) as status1, sum(status = 0) as status0
from t;

在您的情况下,您也可以将其写为:

select sum(status) as status1, sum(1 - status) as status0
from t;

答案 1 :(得分:1)

我会使用CASE语句来检查你的价值。

SELECT SUM(CASE WHEN [status] = 1 THEN 1 ELSE 0 END) AS Status1,
    SUM(CASE WHEN [status] = 0 THEN 1 ELSE 0 END) AS Status0
FROM tbl;