Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use SUM for bit columns?

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.

like image 962
Bruno Pessanha Avatar asked Nov 26 '15 12:11

Bruno Pessanha


People also ask

Can you sum bit SQL?

SQL Server doesn't allow it because it's ambiguous because bit columns are often boolean values or bitmasks.

How do I sum a specific column in SQL?

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.

How do you sum a column in a query?

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.


1 Answers

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 
like image 181
Devart Avatar answered Sep 23 '22 14:09

Devart