Saturday, July 23, 2011

SQL Aggregate BIT Columns with Group By


A common problem you run across in SQL programming is the need to group a series of records that contain bit fields and you need to determine the appropriate value.  If you were to try it using the MAX/MIN operators to achieve the equivalent AND/OR result of the bit field or even the SUM operator you will get one of the following errors.
Operand data type bit is invalid for max operator
or
Operand data type bit is invalid for min operator
or
Operand data type bit is invalid for sum operator
 The answer to the problem is to first cast the bit field to an integer (INT) datatype and perform the MAX or MIN operator on that and then cast it back to a BIT field.
For example suppose you have 3 record sets from a table called “Stores” with a bit field called “ObserveDaylightSavings” and your goal is to determine if any of the records have this bit set to “1″ or true, meaning that at least one of the stores observes daylight savings time.  This is the equivalent tothe “OR” logic operator where if any of the colums are true then the result is true.  The SQL to determine this is as follows:
SELECT CAST(MAX(CAST(ObserveDaylightSavings as INT)) AS BIT) AS ObserveDaylightSavings
FROM Stores
The result would be “1″ if any of the records has the value set to “1″ or “true” or “0″ if none of them had a bit value of “1″.
The reverse is just as simple.  For example if you needed to determine if all of the stores observed daylight savings time, then this would be the equivalent “AND” logical operator.  Meaning if all of the stores had the “ObserveDaylightSavings” bit field set to “1″ or “true” then the result of the query would be “1″.  If any one of them did not have the field set to “1″, then the resulting column would be “0″ or “false”.  The SQL to do that is as follows:
SELECT CAST(MIN(CAST(ObserveDaylightSavings as INT)) AS BIT) AS ObserveDaylightSavings
FROM Stores
The only difference is that the MAX was replaced with the MIN operator.
So basically, if you are faced with the error:  “Operand data type bit is invalid for max operator” or “Operand data type bit is invalid for min operator” or even “Operand data type bit is invalid for sum operator” then the answer is to cast the value to an INT and then back to a BIT and you’ll achieve an equivalent AND/OR type of solution for the field.  This allows you to aggregate bit fields in SQL.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Deep's | Bloggerized by Deep - Deep's Templates | ElearSQL-Server