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.
SQL Server doesn't allow it because it's ambiguous because bit columns are often boolean values or bitmasks.
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.
You can sum a column of numbers in a query by using a type of function called an aggregate function. Aggregate functions perform a calculation on a column of data and return a single value. Access provides a variety of aggregate functions, including Sum, Count, Avg (for computing averages), Min and Max.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With