SQL Server:将多个度量列汇总为1列

时间:2019-03-12 15:57:04

标签: sql sql-server group-by unpivot

我是SQL的新手,请在询问之前尽一切努力搜索此主题。

我有以下格式的数据:

Current State Format

我需要这种格式:

Need in this format

我意识到这可能很容易,但是任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在SQL SERVER上尝试此操作:

CREATE TABLE TestPvt (Year varchar(32), January int, february int,  
    March int);  
GO  
INSERT INTO TestPvt VALUES ('Actual 2019',700,220,456);  
INSERT INTO TestPvt VALUES ('Budget 2019',200,752,500);  

SELECT Year, Month, Amount  
FROM   
   (SELECT Year, January, february, March  
   FROM TestPvt) p  
UNPIVOT  
   (Amount FOR Month IN   
      (January, february, March)  
)AS unpvt;

结果是:

Year    Month   Amount
Actual 2019 January 700
Actual 2019 february    220
Actual 2019 March   456
Budget 2019 January 200
Budget 2019 february    752
Budget 2019 March   500