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.

6 Answers 6

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
1
  • 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, 2017 at 5: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.

1
  • 2
    PostgreSQL works with SUM(CAST(Passed as Integer)) PASS, SUM(1 - CAST(Passed AS Integer) FAIL.
    – karmakaze
    Dec 8, 2012 at 5:11
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)
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
2
  • This will result in the number of results including both pass and fail. Should be Sum Jan 31, 2022 at 16:01
  • 1
    No it won't. If the value of ColumnName doesn't match then it will return null, which isn't counted by COUNT.
    – mrdenny
    Feb 1, 2022 at 18:21
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
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.