[英]How to pivot in SQL for achieving multilevel headers
Pivot multilevel header without performing any aggregation 枢转多级标头而不执行任何聚合
Unsure of how to really get this multilevel headings with no aggregation in the pivot, as you would notice the current and desired layout. 由于您会注意到当前和所需的布局,因此不确定如何真正获得此多级标题,而不会在枢轴中进行任何汇总。
With pivot_data as
(
Select * from Table1
)
Select id, 3/31/2001, 6/30/2001, 9/30/2001, 12/31/2001, 3/31/2002, 6/30/2002, 9/30/2002, 12/31/2002
from pivot_data
Pivot(Max(Comm) For Dt in (3/31/2001, 6/30/2001, 9/30/2001, 12/31/2001, 3/31/2002, 6/30/2002, 9/30/2002, 12/31/2002)) P1
Pivot(Max(Norm)) For Dt in (3/31/2001, 6/30/2001, 9/30/2001, 12/31/2001, 3/31/2002, 6/30/2002, 9/30/2002, 12/31/2002)) P2
Pivot(Max(Team)) For Dt in (3/31/2001, 6/30/2001, 9/30/2001, 12/31/2001, 3/31/2002, 6/30/2002, 9/30/2002, 12/31/2002)) P3
I'm trying to achieve this layout: 我正在尝试实现以下布局:
Comm Comm Comm Comm Norm Norm Norm Norm
id 3/31/2018 6/30/2018 9/30/2018 12/31/2018 3/31/2018 6/30/2018 9/30/2018 12/31/2018
1 55 0 54 0 0 3 0 3
2 0 41 0 43 3 0 4 0
From Current layout:
id Date Comm Norm
1 3/31/2018 55
1 6/30/2018 3
1 9/30/2018 54
1 12/31/2018 3
2 3/31/2018 3
2 6/30/2018 41
2 9/30/2018 4
2 12/31/2018 43
You can use conditional aggregation this way: 您可以通过以下方式使用条件聚合:
select id,
sum(case when Date = '3/31/2018' then Comm end) as 'Comm 3/31/2018',
sum(case when Date = '6/30/2018' then Comm end) as 'Comm 6/30/2018',
sum(case when Date = '9/30/2018' then Comm end) as 'Comm 9/30/2018',
sum(case when Date = '12/31/2018' then Comm end) as 'Comm 12/31/2018',
sum(case when Date = '3/31/2018' then Norm end) as 'Norm 3/31/2018',
sum(case when Date = '6/30/2018' then Norm end) as 'Norm 6/30/2018',
sum(case when Date = '9/30/2018' then Norm end) as 'Norm 9/30/2018',
sum(case when Date = '12/31/2018' then Norm end) as 'Norm 12/31/2018'
from mytable
group by id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.