How can I use SUM for bit columns?

Bruno Pessanha picture Bruno Pessanha · Nov 26, 2015 · Viewed 31.2k times · Source

How can use the function SUM() for bit columns in T-SQL?

When I try do it as below:

SELECT SUM(bitColumn) FROM MyTable;

I get the error:

Operand data type bit is invalid for sum operator.

Answer

Devart picture Devart · Nov 26, 2015
SELECT SUM(CAST(bitColumn AS INT))
FROM dbo.MyTable

need to cast into number

or another solution -

SELECT COUNT(*)
FROM dbo.MyTable
WHERE bitColumn = 1