SQL Server - 多个聚合数据透视表

时间:2017-02-14 14:34:07

标签: sql-server pivot-table

我有一张如下表......

Serv    nm   Mnth  sc   se
F       01   Jan   100  5
M       01   Jan   200  2
A       01   Jan   100  7 
F       02   Feb   200  3
A       02   Feb   100  3 

我怎么能像......那样改变它。

nm   Mnth  SumF(sc)  SumF(se)  SumM(sc) SumF(se) SumA(sc) SumA(se)
01   Jan   100       5         200      2        100      7
02   Jan   200       3         NULL     NULL     100      3   

2 个答案:

答案 0 :(得分:2)

假设你需要去 DYNAMIC

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName('Sum'+Serv+'(sc)')+','+QuoteName('Sum'+Serv+'(se)') From Yourtable  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select [nm],[Mnth],' + @SQL + '
From (
        Select [nm]
              ,[Mnth]
              ,C.*
         From YourTable A
         Cross Apply (Values (''Sum''+A.Serv+''(sc)'',A.sc)
                            ,(''Sum''+A.Serv+''(se)'',A.se)
                     ) C (Item,Value)
     ) A
 Pivot (sum(Value) For [Item] in (' + @SQL + ') ) p'
Exec(@SQL);

<强>返回

enter image description here

生成的SQL(如果你不需要动态)

Select [nm],[Mnth],[SumA(sc)],[SumA(se)],[SumF(sc)],[SumF(se)],[SumM(sc)],[SumM(se)]
From (
        Select [nm]
              ,[Mnth]
              ,C.*
         From YourTable A
         Cross Apply (Values ('Sum'+A.Serv+'(sc)',A.sc)
                            ,('Sum'+A.Serv+'(se)',A.se)
                     ) C (Item,Value)
     ) A
 Pivot (sum(Value) For [Item] in ([SumA(sc)],[SumA(se)],[SumF(sc)],[SumF(se)],[SumM(sc)],[SumM(se)]) ) p

答案 1 :(得分:1)

您可以先取消该值,以便在同一列中同时获取se和sc,然后像这样执行一个数据透视:

select *
from (
select 
    serv+'_'+t serv, nm, mnth, s 
from t
cross apply (
    values 
        ('sc', sc),
        ('se', se)
    ) x (t, s)
) t pivot (
    sum(s) for serv in (
        [F_sc],[F_se],
        [M_sc],[M_se],
        [A_sc],[A_se]
    )
) as p;

产地:

enter image description here