答案 0 :(得分:1)
虽然建议的副本会让你在那里的一部分,你实际上需要转动,然后转动,像这样。
(哦,请不要发布图片。感谢DDL并节省我们打字和/或猜测。)
CREATE TABLE #Test( Action char, [Key] INT, Old varchar(5), OldValue varchar(5), New varchar(5), NewValue varchar(5));
INSERT INTO #Test VALUES
('U', 123, 'Col1','Dog','Col1','Dog'),
('U', 123, 'Col2','Cat','Col2','Mouse'),
('U', 123, 'Col3','Honey','Col3','Bee'),
('I', 123, NULL,NULL,'Col45','Sun');
SELECT PVT.Action
,PVT.[Key]
,PVT.OldCol1
,PVT.OldCol2
,PVT.OldCol3
,PVT.NewCol1
,PVT.NewCol2
,PVT.NewCol3
,PVT.NewCol45 FROM (
SELECT [Action]
,[Key]
,Label
,Value
FROM #Test
CROSS APPLY (VALUES ('Old'+Old, OldValue), ('New'+New, NewValue)) c(label, value)
)src
PIVOT
(
MAX(VALUE) FOR Label IN (OldCol1, NewCol1, OldCol2, NewCol2, OldCol3, NewCol3, NewCol45)
)PVT
ORDER BY PVT.Action Desc
Action Key OldCol1 OldCol2 OldCol3 NewCol1 NewCol2 NewCol3 NewCol45
------ ----------- ------- ------- ------- ------- ------- ------- --------
U 123 Dog Cat Honey Dog Mouse Bee NULL
I 123 NULL NULL NULL NULL NULL NULL Sun
(2 row(s) affected)
答案 1 :(得分:0)
我想旋转就足够了:
SELECT *
FROM (
SELECT [Action], [Key], 'Old' + Old as [a], OldValue as [Value]
FROM Table1
UNION ALL
SELECT [Action], [Key], 'New' + New, NewValue
FROM Table1
) as p
PIVOT (
MAX([Value]) FOR [a] IN ([OldCol1],[OldCol2],[OldCol3],[NewCol1],[NewCol2],[NewCol3],[NewCol45])
) as pvt
输出:
Action Key OldCol1 OldCol2 OldCol3 NewCol1 NewCol2 NewCol3 NewCol45
I 123 NULL NULL NULL NULL NULL NULL Sun
U 123 Dog Cat Honey Dog Mouse Bee NULL
如果有多个Old
和'New`值,那么您需要动态SQL