views:

424

answers:

4

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.

+2  A: 

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
Matthew Jones
this code has three errors in it, missing two "END" commands and using "WHERE" and not "WHEN" in the CASE.
KM
You are correct, sir! Edited.
Matthew Jones
...yet the OP didn't mind the errors and accepted it...
KM
A: 

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
+2  A: 
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
+2  A: 

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