2015-11-17 77 views
1

我希望能夠根據表中的另一列計算特定值在列中出現的次數。下面是示例表:需要查找存儲在多個列中的值的計數

Color Shape  Col1 Col2 Col3 Col4 Col5 
-------------------------------------------------------- 
Blue Circle  Blue Null Yellow Null Null 
Blue Circle  Blue Null Null Null Black 
Blue Circle  Null Null Null Null Null 
Yellow Square  Null Null Null Null Null 
Yellow Square  Null Yellow Null Null Null 
Yellow Square  Null Null Null Null Null 
Yellow Square  Green Null Null Yellow Null 
Yellow Square  Null Null Null Null Null 
Green Rectangle Null Null Null Null Green 
Orange Triangle Gray White Null Null Orange 
Orange Triangle Null Orange Null Null Null 

我需要的結果是見下表:

Color Shape  Col1 Col2 Col3 Col4 Col5 
---------------------------------------------------- 
Blue Circle  2 0  0  0  0 
Yellow Square  0 1  0  1  0 
Green Rectangle 0 0  0  0  1 
Orange Triangle 0 1  0  0  1 

這個查詢是不是給我的願望了:

select 
    Color, Shape, 
    count(Col1) as Col1, count(Col2) as Col2, 
    count(Col3) as Col3, count(Col4) as Col4, count(Col5) as Col5 
from 
    Sample_Table 
group by 
    Color, Shape 

有誰知道如何獲得慾望輸出?

+0

您的查詢似乎沒什麼問題。計數應忽略空值。你可以發佈樣本表的dml + ddl嗎? –

+0

@ZoharPeled,OP只想計算內容與'Color'列相同的列......現有的查詢將返回列'NOT NULL'的所有計數... – Shnugo

+0

@Shnugo:顯然你是正確的,我誤解了這個問題。 –

回答

5

使用CASE表達式進行條件計數:

select 
    Color, Shape, 
    count(case when Color = Col1 then 1 end) as Col1, 
    count(case when Color = Col2 then 1 end) as Col2, 
    count(case when Color = Col3 then 1 end) as Col3, 
    count(case when Color = Col4 then 1 end) as Col4, 
    count(case when Color = Col5 then 1 end) as Col5 
from 
    Sample_Table 
group by 
    Color, Shape 
+0

你比我快:-) +1在我身邊 – Shnugo

+0

同樣在這裏:)) – Utsav

+1

@Shnugo,感謝您解決我的錯誤! – jarlh

相關問題