如何从位字段获取真/假计数到两个单独的列

时间:2009-10-07 17:38:34

标签: sql-server tsql sql-server-2008 bit

我需要创建一个查询,将True(1)和False(0)的数量与一个位字段的两个独立列相加。

我正在加入3个表,需要它像:

属性|班级|通过|失败

我将分组属性和类。

6 个答案:

答案 0 :(得分:69)

这样的事情:

SUM(CASE WHEN ColumnName = 1 THEN 1 ELSE 0 END) AS Pass, 
SUM(CASE WHEN ColumnName = 0 THEN 1 ELSE 0 END) AS Fail

答案 1 :(得分:12)

这有效(至少在SQL 2008中)

SELECT SUM(Passed + 0) PASS , SUM(1 - Passed) FAIL

我在第一笔中将Passed加0作为从bit转换为int的简单方法,因为你不能直接对位进行求和。

答案 2 :(得分:3)

SELECT
    Attribute,
    Class,
    SUM(CASE BitField WHEN 1 THEN 1 ELSE 0 END) AS [Pass],
    SUM(CASE BitField WHEN 0 THEN 1 ELSE 0 END) AS [Fail]
FROM 
    Table
GROUP BY
    Attribute,
    Class

答案 3 :(得分:3)

尝试:

declare @table table (columnName bit)
insert into @table values (1)
insert into @table values (1)
insert into @table values (1)
insert into @table values (1)
insert into @table values (1)
insert into @table values (0)
insert into @table values (0)
insert into @table values (0)
insert into @table values (0)

SELECT
    SUM(CASE WHEN ColumnName = 1 THEN 1 ELSE 0 END) AS True1
  , SUM(CASE WHEN ColumnName = 0 THEN 1 ELSE 0 END ) AS False0
from @Table

输出:

True1       False0
----------- -----------
5           4

(1 row(s) affected)

答案 4 :(得分:2)

另一种选择是

SELECT Attribute, Class
       COUNT(CASE WHEN ColumnName = 1 THEN 1 END) Pass,
       COUNT(CASE WHEN ColumnName = 0 THEN 1 END) Fail FROM YourTable 
GROUP BY Attribute, Class

答案 5 :(得分:0)

还有一个选择:

SELECT 
   Attribute, 
   Class,
   COUNT(BoolColumnName = 1 or NULL) Pass,
   COUNT(BoolColumnName = 0 or NULL) Fail 
FROM Table
GROUP BY Attribute, Class