2015-11-17 36 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

相关问题