SQL - 基于多列的组

时间:2013-10-23 16:04:02

标签: sql-server

我有以下表格:

A_ID         Area_Code        Status
1               AAA             2         
2               BBB             1         
3               AAA             2         
4               AAA             3         
5               AAA             2         
6               BBB             2         
7               BBB             1         
8               AAA             4         
9               AAA             5         
10              AAA             4         

我希望结果集如下:

A_Code Count_A_Code Count_Sts1 Count_Sts2 Count_Sts3 Count_Sts4 Count_Sts5

AAA         7            0         3          1        2          1

BBB         3            2         1          0        0          0

请注意,我只有5个雕像。所以我需要雕像作为列..

我感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:0)

select area_code as a_code,
       count(*) as count_a_code,
       sum(case when status = 1 then 1 else 0 end) as code_count_sts1,
       sum(case when status = 2 then 1 else 0 end) as code_count_sts2,
       sum(case when status = 3 then 1 else 0 end) as code_count_sts3,
       sum(case when status = 4 then 1 else 0 end) as code_count_sts4,
       sum(case when status = 5 then 1 else 0 end) as code_count_sts5
from your_table
group by area_code