需要查找存储在多个列中的值的计数

时间:2015-11-17 08:35:31

标签: sql sql-server

我希望能够根据表中的另一列计算特定值在列中出现的次数。以下是样本表:

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

有谁知道如何获得欲望输出?

1 个答案:

答案 0 :(得分: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