简体   繁体   中英

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.

SQL Server does not have such an aggregate function. You could create one using SQLCLR.

But an easier option is to split out each bit and aggregate separately, then add them back together.

For OR

SELECT
  MAX(flags & 1) +
  MAX(flags & 2) +
  MAX(flags & 4) +
  MAX(flags & 8)
FROM #Example
GROUP BY Category

For AND

SELECT
  MIN(flags & 1) +
  MIN(flags & 2) +
  MIN(flags & 4) +
  MIN(flags & 8)
FROM #Example
GROUP BY Category

db<>fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM