Aggregate bitwise-OR in a subquery

后端 未结 10 2025
醉酒成梦
醉酒成梦 2020-11-30 08:46

Given the following table:

CREATE TABLE BitValues ( n int )

Is it possible to compute the bitwise-OR of n for all rows with

10条回答
  •  臣服心动
    2020-11-30 09:01

    You can use a variable and do a "bitwise or" (|) for each row:

    declare @t table (n int)
    insert @t select 1 union select 2 union select 4
    
    declare @i int
    set @i = 0
    
    select  @i = @i | n
    from    @t
    
    select @i
    

    This prints 7. Note that assigning variables in a select is not officially supported.

    In a more strictly SQL way, you can create a table with one row for each bit. This table would have 31 rows, as the 32nd bit is a negative integer. This example uses a recursive CTE to create that table:

    declare @t table (n int)
    insert @t select 1 union select 2 union select 3
    
    ; with bits(nr, pow) as 
    (
        select  1
        ,       1
        union all
        select  nr + 1
        ,       pow * 2
        from    bits
        where   nr <= 30
    )
    select  sum(b.pow)
    from    bits b
    where   exists
            (
            select  *
            from    @t t  
            where   b.pow & t.n > 0
            )
    

    This sums the bits where any bit in the source table is set.

提交回复
热议问题