How can I use SUM for bit columns?

前端 未结 7 1072
栀梦
栀梦 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:25

    Somewhat cryptically:

    declare @Foo as Bit = 1;
    -- @Foo is a Bit.
    select SQL_Variant_Property( @Foo, 'BaseType' );
    -- But adding zero results in an expression with data type Int.
    select SQL_Variant_Property( @Foo + 0, 'BaseType' );
    select Sum( @Foo + 0 );
    
    declare @Samples as Table ( Foo Bit );
    insert into @Samples ( Foo ) values ( 0 ), ( 1 ), ( 0 ), ( 0 ), ( 1 ), ( 1 ), ( 1 ), ( 1 );
    select Sum( Foo + 0 ) from @Samples;
    

    This certainly doesn't improve readability or maintainability, but it is compact.

    0 讨论(0)
提交回复
热议问题