Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the true/false count from a bit field into two separate columns

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.

like image 896
avgbody Avatar asked Oct 07 '09 17:10

avgbody


2 Answers

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 
like image 156
Matthew Jones Avatar answered Sep 21 '22 01:09

Matthew Jones


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.

like image 41
Kenneth Baltrinic Avatar answered Sep 21 '22 01:09

Kenneth Baltrinic