TSQL PIVOT/UNPIVOT 多个汇总列

TSQL PIVOT/UNPIVOT Multiple Summarized Columns

似乎这是一个热门话题,但我似乎无法复制其他答案。

我有 month/year 已针对多个类别汇总的数据。

month   calls   deals   productssold   avgsaleprice 
    1      25       6              7            500
    2      17       2              4            300
    3      15       3              5            600
    4      22       1              1            800
    5      18       7             12            300
    6      12       9             15            250   

我想得到的是这个

    category   1   2   3   4   5   6
       calls  25  17  15  22  18  12
       deals   6   2   3   1   7   9
productssold   7   4   5   1  12  15
avgsaleprice 500 300 600 800 300 250

这是提供数据的查询

declare @summarizedtable table (
 month int,
 calls int,
 deals int,
 productssold int,
 avgsaleprice int)    
 
 insert into @summarizedtable (month, calls, deals, productssold, avgsaleprice)
 values (1,25,6,7,500),
        (2,17,2,4,300),
        (3,15,3,5,600),
        (4,22,1,1,800),
        (5,18,7,12,300),
        (6,12,9,15,250);
        
 select *
   from @summarizedtable

我用过 PIVOT 很多次,但只有一个“类别”的数据。我似乎无法坚持使用多个类别

我会使用 cross apply 进行逆透视,然后使用条件聚合进行透视:

select x.category,
    sum(case when t.month = 1 then val end) month_1,
    sum(case when t.month = 2 then val end) month_2,
    sum(case when t.month = 3 then val end) month_3,
    sum(case when t.month = 4 then val end) month_4,
    sum(case when t.month = 5 then val end) month_5,
    sum(case when t.month = 6 then val end) month_6
from @summarizedtable t
cross apply (values 
    ('calls', t.calls), 
    ('deals', t.deals), 
    ('productssold', t.productssold),
    ('avgsaleprice', t.avgsaleprice)
) as x(category, val)
group by x.category

Demo on DB Fiddle:

category     | month_1 | month_2 | month_3 | month_4 | month_5 | month_6
:----------- | ------: | ------: | ------: | ------: | ------: | ------:
avgsaleprice |     500 |     300 |     600 |     800 |     300 |     250
calls        |      25 |      17 |      15 |      22 |      18 |      12
deals        |       6 |       2 |       3 |       1 |       7 |       9
productssold |       7 |       4 |       5 |       1 |      12 |      15