2017-06-01 22 views
1

對於T-SQL(SQL Server 2016)bit類型,是否有某種方法可實現邏輯AND和邏輯OR的等效聚合?例如,與此表:對於類型爲'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) 

我想創建一個查詢,列出,按類別,如果isRed任何設置(OR),如果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. 

所有其他聚合函數都會出現類似的結果。

回答

3

MINMAX功能,可用於:

SELECT 
    category, 
    MAX(CONVERT(tinyint,isRed)) isAnyRed, 
    MIN(CONVERT(tinyint,isBlue)) isAllBlue 
FROM 
    #Example 
GROUP BY 
    category 

但是你要bit轉換爲某種數值(tinyint),作爲MINMAX工作只能用數字,而不是布爾值。

+2

激將法簡單。很好,謝謝。 –

+1

@JasonC你用'MIN'和'MAX'解決方案是正確的,問題出在'CONVERT'上。樂意效勞! – Backs

0

您可以使用子查詢,如下發現:

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