计算单个查询中的布尔字段值

时间:2014-03-16 16:34:59

标签: mysql sql

我喜欢获取某个字段为1或0的行数。

我的表格如下:

ID | name | my_bool
===================
 1 | foo  | 1
 2 | bar  | 1
 3 | loo  | 0
 4 | zoo  | 1

结果我期待

YES | NO  | percentage
======================
 3  | 1   | 0.3333

YESmy_bool 为真的行数(1),而NO false 的行(0) )

percentageYES的百分比给予NO

4 个答案:

答案 0 :(得分:17)

在MySQL中,您可以使用条件聚合轻松完成此操作:

select sum(my_bool = 1) as yes, sum(my_bool = 0) as no
from table t;

编辑:

百分比非常简单:

select sum(my_bool = 1) as yes, sum(my_bool = 0) as no, avg(my_bool = 0)
from table t;

但是,您的价值表明您正在寻找比率,而不是百分比。为此,你需要注意除以零:

select sum(my_bool = 1) as yes, sum(my_bool = 0) as no,
       (case when sum(my_bool = 1) > 0 then sum(my_bool = 0) / sum(my_bool = 1)
        end)
from table t;

答案 1 :(得分:2)

SELECT SUM(IF(my_bool=1, 1, 0)) AS YES, SUM(IF(my_bool=0, 1, 0)) AS NO
FROM mytable

答案 2 :(得分:2)

这个怎么样?

select
    count(foo.my_bool) as "YES",
    count(bar.my_bool) as "NO",
    (count(bar.my_bool) / count(foo.mybool)) as "percentage"
from
    myTable foo
    left join myTable bar
        on foo.id = bar.id
where
    foo.my_bool = 1
    and bar.my_bool = 0

编辑:请务必防止Gordon Linoff提到的除零。

答案 3 :(得分:0)

这样的事可能吗?

SELECT sum(my_bool) AS Yes, count(ID)-sum(my_bool) AS No FROM mytable