How to get the true/false count from a bit field i

2019-02-11 10:51发布

问题:

I need to create a query that will sum the number of True(1) and False(0) into two separate columns from one bit field.

I'm joining 3 tables and need it to be something like:

Attribute | Class | Pass | Fail

I will be grouping on Attribute and Class.

回答1:

Something like this:

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


回答2:

This works (at least in SQL 2008)

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

I am adding 0 to Passed in the first sum as a short hand way of converting from bit to int since you can't sum bits directly.



回答3:

try:

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)


回答4:

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


回答5:

Another option would be

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


回答6:

there is even one more option:

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