'SQL Aggregate logical operations

Is there a way in T-SQL to aggregate with logical conditions on fields which do not represent single bits?

For example, given this data:

CREATE TABLE #Example       (category int, flags int)
INSERT INTO #Example VALUES (1,            1) -- Binary 0001
INSERT INTO #Example VALUES (1,            2) -- Binary 0010

I'd like a query that does something similar to:

SELECT AND(flags) FROM #Example
GROUP BY Category
-- Expect the result to be 0 because 0001 AND 0010 = 0000

SELECT OR(flags) FROM #Example
GROUP BY Category
-- Expect the result to be 3 because 0010 OR 0001 = 0011

On a single bit field I know you can convert to int and then use max and min, but this would only work on single bit values so doesn't solve the problem.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source