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.
If you’re expecting the result
171, surely you mean binaryORnotAND?In any case, this solution aggregates the values into a variable:
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.