聚合类型为 'bit' 的列的逻辑 AND / OR
Aggregate logical AND / OR for columns with type 'bit'
对于 T-SQL (SQL Server 2016) bit
类型,是否有某种方法可以实现逻辑 AND 和逻辑 OR 的聚合等价物?例如,使用此 table:
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)
我想创建一个查询,按类别列出 any of isRed
是否设置(或),如果 isBlue
的所有 已设置 (AND),例如输出:
category anyRed allBlue
1 1 0
2 0 1
也就是说,我喜欢像这样的东西:
SELECT
category,
OR(isRed) isAnyRed,
AND(isBlue) isAllBlue
FROM
#Example
GROUP BY
category
我唯一能想到的尝试是:
SELECT
category,
MAX(isRed) isAnyRed,
MIN(isBlue) isAllBlue
FROM
#Example
GROUP BY
category
哪个不起作用,给出错误:
Operand data type bit is invalid for max operator.
所有其他聚合函数都会出现类似的结果。
MIN
和MAX
函数可以使用:
SELECT
category,
MAX(CONVERT(tinyint,isRed)) isAnyRed,
MIN(CONVERT(tinyint,isBlue)) isAllBlue
FROM
#Example
GROUP BY
category
但是您必须将 bit
转换为某个数值 (tinyint
),因为 MIN
和 MAX
仅适用于数字,不适用于布尔值。
您可以使用子查询查找如下:
Select Category, AnyRed = Case When SmRed > 0 then 1 else 0 End,
AllBlue = Case When SmBlue = Cnt then 1 else 0 End from (
select category, SMRed = sum(iif(isred=1,1,0)), SMBlue = Sum(iif(isBlue=1,1,0)), Cnt= Count(id) from #Example
group by category
) a
对于 T-SQL (SQL Server 2016) bit
类型,是否有某种方法可以实现逻辑 AND 和逻辑 OR 的聚合等价物?例如,使用此 table:
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)
我想创建一个查询,按类别列出 any of isRed
是否设置(或),如果 isBlue
的所有 已设置 (AND),例如输出:
category anyRed allBlue
1 1 0
2 0 1
也就是说,我喜欢像这样的东西:
SELECT
category,
OR(isRed) isAnyRed,
AND(isBlue) isAllBlue
FROM
#Example
GROUP BY
category
我唯一能想到的尝试是:
SELECT
category,
MAX(isRed) isAnyRed,
MIN(isBlue) isAllBlue
FROM
#Example
GROUP BY
category
哪个不起作用,给出错误:
Operand data type bit is invalid for max operator.
所有其他聚合函数都会出现类似的结果。
MIN
和MAX
函数可以使用:
SELECT
category,
MAX(CONVERT(tinyint,isRed)) isAnyRed,
MIN(CONVERT(tinyint,isBlue)) isAllBlue
FROM
#Example
GROUP BY
category
但是您必须将 bit
转换为某个数值 (tinyint
),因为 MIN
和 MAX
仅适用于数字,不适用于布尔值。
您可以使用子查询查找如下:
Select Category, AnyRed = Case When SmRed > 0 then 1 else 0 End,
AllBlue = Case When SmBlue = Cnt then 1 else 0 End from (
select category, SMRed = sum(iif(isred=1,1,0)), SMBlue = Sum(iif(isBlue=1,1,0)), Cnt= Count(id) from #Example
group by category
) a