I want to write the following query:
SELECT ..., MIN(SomeBitField), ...
FROM ...
WHERE ...
GROUP BY ...
The problem is, SQL Server does not like it, when I want to calculate the minimum value of a bit field it returns the error Operand data type bit is invalid for min operator.
I could use the following workaround:
SELECT ..., CAST(MIN(CAST(SomeBitField AS INT)) AS BIT), ...
FROM ...
WHERE ...
GROUP BY ...
But, is there something more elegant? (For example, there might be an aggregate function, that I don’t know, and that evaluates the logical and of the bit values in a field.)
Since there are only two options for
BIT, just use a case statement:This has the advantage of:
BITfields pretty much never get used)EXISTSand again for theCASE)It is a little more code to write but it shouldn’t be terrible. If you have multiple values to check you could always encapsulate your larger result set (with all the
JOINandFILTERcriteria) in aCTEat the beginning of the query, then reference that in theCASEstatements.