Aggregate bitfield values with binary OR

扶醉桌前 提交于 2019-12-24 11:28:40

问题


I have a table with int values being used as bitfields (where each bit is a flag).

Now I would like to aggregate them with a binary operation (in my case OR) so that:

SELECT 1 AS bitfield
INTO #TABLE
UNION ALL SELECT 1 + 2 + 8 + 32
UNION ALL SELECT 2 + 128
UNION ALL SELECT 2 + 32

SELECT AND_AGGR(bitfield) -- Invalid because AND_AGGR doesn't exist
FROM #TABLE

DROP #TABLE

would result in the value 171

What would be a good way to do this that hopefully doesn't require a lot of | and MAX (but if you must, you must)?

I am using MS SQL Server 2008 myself, but solutions on other servers are also of interest.


回答1:


If you're expecting the result 171, surely you mean binary OR not AND?

In any case, this solution aggregates the values into a variable:

SELECT 1 AS bitfield
INTO #TABLE
UNION ALL SELECT 1 + 2 + 8 + 32
UNION ALL SELECT 2 + 128
UNION ALL SELECT 2 + 32

DECLARE @i int = 0

SELECT @i = @i | bitfield
FROM #TABLE

SELECT @i

DROP TABLE  #table

This might not meet your requirements if you want to group the aggregation by another field.

It is also unlikely to perform well on a large table.




回答2:


On MySQL and PostgreSQL you can use BIT_OR.

I don't think SQL Server has this aggregate function.

You could do it with lots of MAX and & as you said:

MAX(x & 1) + MAX(x & 2) + ... + MAX(x & 128)


来源:https://stackoverflow.com/questions/10225885/aggregate-bitfield-values-with-binary-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!