繁体   English   中英

我应该使用PIVOT还是其他

[英]Should I use PIVOT or something else

我有许多使用CTE语句的SQL代码来汇总数据,最终使我陷入类似这样的情况

Bldgcode     Business        Seat_Count     Area  
A012345      Bus 1            1             1234  
A012345      Bus 2            3             3456  
B1234        Bus 1            4             6789  
B1234        Bus 3            6             4321  

我想转置/旋转显示最终结果集,如下所示

Bldgcode    Bus 1 Seat    Bus 1 Area    Bus 2 Seat    Bus 2 Area   Bus 3 Seat  Bus 3 Area  
A012345     1              1234           3             3456        0          0
B1234       4              6789           0              0          6          4321

我希望“业务”列是动态的,因为我有15多个,并且不想单独列出每个字段,此外,有时候在数据中会出现一个新的“业务”,而我需要另外一组列。

我看过PIVOT,但由于我的知识有限,无法使它正常工作,对编码的任何帮助将不胜感激

谢谢

只需使用条件聚合:

select Bldgcode,
       max(case when Business = 'Bus 1' then Seat_Count end) as bus1_seats,
       max(case when Business = 'Bus 1' then area end) as bus1_area,
       max(case when Business = 'Bus 2' then Seat_Count end) as bus2_seats,
       max(case when Business = 'Bus 2' then area end) as bus2_area
from t
group by Bldgcode;

暂无
暂无

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

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