问题
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