我希望能夠根據表中的另一列計算特定值在列中出現的次數。下面是示例表:需要查找存儲在多個列中的值的計數
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
有誰知道如何獲得慾望輸出?
您的查詢似乎沒什麼問題。計數應忽略空值。你可以發佈樣本表的dml + ddl嗎? –
@ZoharPeled,OP只想計算內容與'Color'列相同的列......現有的查詢將返回列'NOT NULL'的所有計數... – Shnugo
@Shnugo:顯然你是正確的,我誤解了這個問題。 –