42

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.

Tom H
  • 46,766
  • 14
  • 87
  • 128
avgbody
  • 1,382
  • 3
  • 15
  • 31

6 Answers6

77

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
SteveC
  • 15,808
  • 23
  • 102
  • 173
Matthew Jones
  • 25,644
  • 17
  • 102
  • 155
  • 1
    I went down the rabbit hole of trying to use a PIVOT, when this was all I needed - so much easier. Thanks! – BlueSix Apr 20 '17 at 05:46
13

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.

Kenneth Baltrinic
  • 2,941
  • 2
  • 28
  • 45
4

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)
KM.
  • 101,727
  • 34
  • 178
  • 212
3

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
mrdenny
  • 4,990
  • 2
  • 21
  • 28
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
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
0

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
va-dev
  • 157
  • 1
  • 7