How to pivot in SQL for achieving multilevel headers

143 views Asked by At

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
1

There are 1 answers

10
Neeraj Agarwal On

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