Aggregate bitwise-OR in a subquery

后端 未结 10 1971
醉酒成梦
醉酒成梦 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:16

    Are you looking for something like this?

    EDIT: As noted in other comments, this answer was based on the assumption that the BitValues table would only contain powers of 2. I tried to read between the lines of the question and infer a use for the inline subquery.

    declare @BitValues table (
        n int
    )
    
    declare @TestTable table (
        id int identity,
        name char(10),
        BitMappedColumn int
    )
    
    insert into @BitValues (n)
        select 1 union all select 2 union all select 4
    
    insert into @TestTable
        (name, BitMappedColumn)
        select 'Joe', 5 union all select 'Bob', 8
    
    select t.id, t.name, t.BitMappedColumn
        from @TestTable t
            inner join (select SUM(n) as BitMask from @BitValues) b
                on t.BitMappedColumn & b.BitMask <> 0
    

提交回复
热议问题