我需要转置数据并重新排序 - 数据每月都在变化,但列名仍然是静态的

时间:2016-11-21 21:43:22

标签: sql-server tsql

原始文件示例:

enter image description here

请求帮助转换为此(这需要每月运行并更新)

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用UNION创建类似的内容:

-- Example table
WITH T (A,B,C,D,E,F,[Jan-OCV],[Feb-OCV],[Mar-OCV],[OWNER],[Jan-ACT],[Feb-ACT],[Mar-ACT])AS
(SELECT 'AA11','A1',777,'XYZ',222,'aasd',123,231,199,'ZZZZ',123,456,789
 UNION ALL
 SELECT 'BB22','A2',8777,'XYZZZZ',3333,'bbbbbb',223,433,231,'YYYYY',225,437,231
 UNION ALL
 SELECT 'CC12','A3',9777,'ZZZ',567,'asdfasfdaasd',788,785,789,'TTTTT',599,759,795
)
-- Query 

SELECT A,B,D,C_E,[OWNER],[Month],OCV, ACT, F 
FROM 
(
SELECT A,B,D,NULL as C_E, [OWNER],'Jan' as [Month],[Jan-OCV] as OCV, [Jan-ACT] as ACT, F, 1 as [Order]
FROM T
UNION ALL
SELECT A,B,D,NULL as C_E, [OWNER],'Feb' as [Month],[Feb-OCV] as OCV, [Feb-ACT] as ACT, F, 2 as [Order]
FROM T
UNION ALL
SELECT A,B,D,NULL as C_E, [OWNER],'Mar' as [Month],[Mar-OCV] as OCV, [Mar-ACT] as ACT, F, 3 as [Order]
FROM T
UNION ALL
SELECT A,B,D, C as [C_E], [OWNER],NULL as [Month],C as OCV, NULL as ACT, F, 4 as [Order]
FROM T
UNION ALL
SELECT A,B,D, E as [C_E], [OWNER],NULL as [Month],E as OCV, NULL as ACT, F, 5 as [Order]
FROM T
) as T1 ORDER BY A,B,D,[Order]