Aggregate bitwise-OR in a subquery

后端 未结 10 1973
醉酒成梦
醉酒成梦 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
    
    0 讨论(0)
  • 2020-11-30 09:17

    Your best bet for a readable and re-usable solution would be to write a a custom CLR Aggregate to perform bitwise or. A tutorial for creating this type of operation can be found here: http://msdn.microsoft.com/en-us/library/91e6taax(VS.80).aspx

    0 讨论(0)
  • 2020-11-30 09:19

    I see this post is pretty old and there are some useful answers but this is a pretty crazy straight forward method...

    Select  
        SUM(DISTINCT(n & 0x01)) +
        SUM(DISTINCT(n & 0x02)) +
        SUM(DISTINCT(n & 0x04))
        as OrN
    From BitValues
    
    0 讨论(0)
  • 2020-11-30 09:19

    Preparations:

    if object_id(N'tempdb..#t', N'U') is not null drop table #t;
    create table #t ( n int );
    insert into #t values (1), (2), (4), (3);
    

    Solution:

    select max(n & 8) + max(n & 4) + max(n & 2) + max(n & 1) from #t;
    
    0 讨论(0)
提交回复
热议问题