|
我有下表,但不确定能否透视表中的一些列:% B+ O2 U3 C1 ? J
CREATE TABLE #test ( id int,Area varchar(10),[grouping] varchar(15),task_1 int,task_2 int)INSERT INTO #test Values (10,'A','HighNeeds',1,10)INSERT INTO #test Values (10,'B','HighNeeds',1,12)INSERT INTO #test Values (12,'C','Non HighNeeds',2,14)select * from #test-------------------------------------------------id Area grouping task_1 task_210 A HighNeeds 1010 B HighNeeds 1212 C Non HighNeeds 2 1444What I'm trying to get is:-------------------------------------------------id Area Tasks HighNeeds Non HighNeeds 10 A task_1 1 1 NULL10 A task_2 10 NULL10 B task_1 1 1 NULL10 B task_ 22 12 NULL12 C task_1 NULL C takk_2 NULL 基本上,我试图保留它ID和Area列,但数据和任务分组。
' n0 [. Y3 Y( }" R/ o ) n4 V% Q/ ~+ t% L3 R
解决方案: ' |& I" [6 U% r2 B) I. K
这很棘手-你需要支点Grouping列,逆透视task_1和task_2为行值:# X# ]6 c. @% g7 ?" w
SELECT *FROM( SELECT id,Area,grouping,tskCount,Task FROM test UNPIVOT tskCount for Task in (task_1,task_2) ) unpvt) XPIVOT( SUM(tskCount) for grouping in (HighNeeds,[Non HighNeeds]))pvt;sqlfiddle |
|