简体   繁体   English

将sql输出转换为以下格式

[英]Convert sql output to following format

I want to convert sql out put to following format. 我想将sql输出转换为以下格式。 Here is my table. 这是我的桌子。

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

In Need Output like below one.Do I need to apply pivot table. 在需求输出中,如下所示。我是否需要应用数据透视表。

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

I am a fan of conditional aggregation for this purpose: 为此,我喜欢条件聚合:

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

Yes you will need pivot & your code would also work along with quote's : 是的,您将需要数据透视,您的代码也可以与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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM