将sql输出转换为以下格式

时间:2019-05-10 10:33:34

标签: sql

我想将sql输出转换为以下格式。 这是我的桌子。

Id  Country Code    Totalcount
1   India   20      120
2   India   21      121
3   India   22      122
4   India   23      123
5   India   24      124
6   US      20      220
7   US      21      221
8   Us      22      222
9   UK      23      323
10  UK      24      324

Select Country, 20,21,22,23,24,25
from
(
   Select Country,StatusCode,Totalcount from StatusDetails
) as SourceTable
Pivot
(
 sum(Totalcount) for StatusCode in (20,21,22,23,24,25)
) as PivotTable

在需要输出中,如下所示。我是否需要应用数据透视表。

Country 20  21  22  23  24
India   120 121 122 123 124
US      220 221 222     
UK                  323 324

2 个答案:

答案 0 :(得分:2)

为此,我是条件聚合的粉丝:

select country,
       max(case when code = 20 then totalcount end) as cnt_20,
       max(case when code = 21 then totalcount end) as cnt_21,
       max(case when code = 22 then totalcount end) as cnt_22,
       max(case when code = 23 then totalcount end) as cnt_23,
       max(case when code = 24 then totalcount end) as cnt_24
from sourcetable
group by country

答案 1 :(得分:0)

是的,您将需要数据透视表,并且您的代码也可以与quote一起使用:

select pt.*
from (select Country, Code, Totalcount 
      from sourcetable
     )as SourceTable Pivot
     (sum(Totalcount) for Code in ([20],[21],[22],[23],[24],[25])
     )as pt;