如何从一个位域获得真/假计数到两个单独的列

我需要创build一个查询,将True(1)和False(0)的数量从一个位字段中分成两个单独的列。

我join了3张桌子,需要它是这样的:

属性| 类| 通过| 失败

我将分组在属性和类。

像这样的东西:

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

这工作(至less在SQL 2008)

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

在第一个和中,我将0加到Passed中,作为从位转换为int的简短方式,因为不能直接对位进行求和。

尝试:

 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 

OUTPUT:

 True1 False0 ----------- ----------- 5 4 (1 row(s) affected) 
 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 

另一个select是

 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