为“位”类型的列聚合逻辑 AND / OR

Jas*_*n C 2 sql t-sql sql-server aggregate sql-server-2016

对于 T-SQL (SQL Server 2016)bit 类型,是否有某种方法可以实现逻辑 AND 和逻辑 OR 的聚合等效?例如,使用此表:

CREATE TABLE #Example       (id int, category int, isRed bit, isBlue bit)
INSERT INTO #Example VALUES (     1,            1,         1,          1)
INSERT INTO #Example VALUES (     2,            1,         0,          0)
INSERT INTO #Example VALUES (     3,            1,         1,          0)
INSERT INTO #Example VALUES (     4,            2,         0,          1)
INSERT INTO #Example VALUES (     5,            2,         0,          1)
INSERT INTO #Example VALUES (     6,            2,         0,          1)
Run Code Online (Sandbox Code Playgroud)

我想创建一个查询,列表,每个类别,如果任何isRed设置(OR),如果所有isBlue设置(AND),如输出:

category  anyRed  allBlue
       1       1        0
       2       0        1
Run Code Online (Sandbox Code Playgroud)

也就是说,我想要这样的东西:

SELECT
  category,
  OR(isRed) isAnyRed,
  AND(isBlue) isAllBlue
FROM
  #Example
GROUP BY
  category
Run Code Online (Sandbox Code Playgroud)

我唯一能想到的尝试是:

SELECT
  category,
  MAX(isRed) isAnyRed,
  MIN(isBlue) isAllBlue
FROM
  #Example
GROUP BY
  category
Run Code Online (Sandbox Code Playgroud)

哪个不起作用,给出错误:

Operand data type bit is invalid for max operator.
Run Code Online (Sandbox Code Playgroud)

所有其他聚合函数都会出现类似的结果。

Bac*_*cks 5

MINMAX函数可以使用:

SELECT
  category,
  MAX(CONVERT(tinyint,isRed)) isAnyRed,
  MIN(CONVERT(tinyint,isBlue)) isAllBlue
FROM
  #Example
GROUP BY
  category
Run Code Online (Sandbox Code Playgroud)

但是您必须转换bit为某个数值 ( tinyint), asMIN并且MAX只能处理数字,而不是布尔值。