我有一张如下表......
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
答案 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);
<强>返回强>
生成的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)