假设我在数据库表中有一个 bool 字段,我想统计有多少为 1 有多少为 0。目前我正在做:
SELECT 'yes' AS result, COUNT( * ) AS num
FROM `table`
WHERE field = 1
UNION
SELECT 'no' AS result, COUNT( * ) AS num
FROM `table`
WHERE field = 0;
有没有更简单的方法来获得结果,即使没有错误值我仍然会得到:
----------
|yes | 3 |
|no | 0 |
----------
最佳答案
一种方法是外连接到查找表。因此,创建一个将字段值映射到名称的查找表:
create table field_lookup (
field int,
description varchar(3)
)
并填充它
insert into field_lookup values (0, 'no')
insert into field_lookup values (1, 'yes')
现在下一位取决于您的 SQL 供应商,下面有一些 Sybase(或 SQL Server)特定位(外连接语法和 isnull 将空值转换为零):
select description, isnull(num,0)
from (select field, count(*) num from `table` group by field) d, field_lookup fl
where d.field =* fl.field
关于sql - bool 字段为 0 的 Count(*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3341284/