2013-02-19 74 views
2

具有相同的價值觀2列值的計數我有與幾個其他列總和或基於在SQL服務器

ColorA 
ColorB 
Status 

在此DB這個樣子的數據命名列的數據庫表。

ColorA  ColorB Status 
---------  --------- --------- 
GREEN   NULL  YES 
GREEN   NULL  YES 
RED    GREEN  NO 
RED    GREEN  YES 

我想要的結果是什麼這取決於狀態=「YES」

Color Count 
GREEN 3 
RED  1 

我還定義表,保存所有顏色等。

如何構建這個SQL查詢,這將導致前面提到的輸出?我有一個查詢,但我正在使用LEFT Join,然後做一個沒有給出正確結果的UNION。

回答

4

這應該工作:

SELECT a.color, 
     Count(a.color) AS Count 
FROM (SELECT colora AS color 
     FROM table1 
     WHERE status = 'YES' 
       AND colora IS NOT NULL 
     UNION ALL 
     SELECT colorb 
     FROM table1 
     WHERE status = 'YES' 
       AND colorb IS NOT NULL) a 
GROUP BY a.color 

結果

| COLOR | COUNT | 
----------------- 
| GREEN |  3 | 
| RED |  1 |

See the demo

+1

+1 - 尼斯的答案! – sgeddes 2013-02-19 03:56:46

+0

+1謝謝你解決了我的問題... – aioracle 2013-02-19 06:19:35

0

從你給的例子,你想知道每個ColorA或ColorB記錄的計數

SELECT Color, SUM(Total) AS Count 
FROM (
    SELECT ColorA as Color, SUM(CASE WHEN Status = 'Yes' THEN 1 ELSE 0 END) AS Total 
    Group By ColorA 
UNION 
    SELECT ColorB as Color, SUM(CASE WHEN Status = 'Yes' THEN 1 ELSE 0 END) AS Total 
    Group By ColorB 
) U 
GROUP BY Color 
0

此作品在SQL Server,MySQL和PostgreSQL(SQLFiddle demo):

SELECT color, sum(cnt) AS count FROM (
    SELECT colorA AS color, count(*) AS cnt 
    FROM mytable 
    WHERE status = 'YES' 
    GROUP BY colorA 
UNION ALL 
    SELECT colorB AS color, count(*) AS cnt 
    FROM mytable 
    WHERE status = 'YES' 
    GROUP BY colorB 
) AS x 
WHERE color IS NOT NULL 
GROUP BY color 
+0

謝謝 - 這也適用(Y) – aioracle 2013-02-19 06:19:08