How can I use SUM for bit columns?

前端 未结 7 1071
栀梦
栀梦 2021-01-01 10:45

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 e

相关标签:
7条回答
  • 2021-01-01 11:01

    You could consider 0 as nulls and simply count the remaining values:

    SELECT count(nullif(bitColumn, 0))
    FROM MyTable;
    
    0 讨论(0)
  • 2021-01-01 11:01
    SELECT SUM(bitColumn * 1) FROM dbo.MyTable
    

    Converts the bit into int, by multiplication, clean and simple

    0 讨论(0)
  • 2021-01-01 11:02

    You can achieve by using CONVERT,

    SELECT SUM(CONVERT(INT, bitColumn)) FROM MyTable
    
    0 讨论(0)
  • 2021-01-01 11:16

    You could use SIGN function:

    CREATE TABLE tab_x(b BIT);
    INSERT INTO tab_x(b) VALUES(1),(0),(0),(NULL),(0),(1);
    
    SELECT SUM(SIGN(b))
    FROM tab_x;
    -- 2
    

    DBFiddle Demo

    0 讨论(0)
  • 2021-01-01 11:21
    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
    
    0 讨论(0)
  • 2021-01-01 11:24

    You can use CAST and CONVERT function for data type to integer or number data type.

    Try this code blocks :

    SELECT SUM(CAST(bitColumn AS INT)) as bitColumn
    FROM MyTable
    

    or

    SELECT CONVERT(INT, bitColumn) 
    FROM MyTable
    
    0 讨论(0)
提交回复
热议问题