SQL Pivot / Transform

时间:2014-05-21 16:25:33

标签: sql-server tsql sql-server-2012

使用SQL Server 2012,我有下表

CREATE TABLE [dbo].[DataField](
    [DisplayName] [varchar](255) NOT NULL,
    [DisplayValue] [varchar](255) NOT NULL
) ON [PRIMARY]

GO

我运行此插入查询

INSERT INTO dbo.DataField VALUES 
('Column 1', '10'),
('Column 2', '20'),
('Column 1', '30'),
('Column 2', '40'),
('Column 1', '50'),
('Column 2', '60'),
('Column 1', '70'),
('Column 2', '80')

我运行此查询...

SELECT DisplayName, DisplayValue FROM [dbo].[DataField]

返回

Field      |   Value
'Column 1' |    10
'Column 2' |    20
'Column 1' |    30
'Column 2' |    40
'Column 1' |    50
'Column 2' |    60

我想写一个输出像这样的结果的查询..

Column 1 | Column 2
10       | 20
30       | 40
50       | 60

我可以使用Pivot或Unpivot或其他一些tsql来执行此操作吗?

1 个答案:

答案 0 :(得分:2)

在@ BogdanSahlean的回答中,您可以使用row_number而不是dense_rank,而不是SELECT z.[Column A], z.[Column B] FROM ( SELECT x.DisplayName, x.DisplayValue, x.GroupNum FROM ( SELECT * , (DENSE_RANK() OVER(PARTITION BY df.DisplayName ORDER BY df.DataFieldID)) AS GroupNum FROM @t df ) x ) y PIVOT( MAX(y.DisplayValue) FOR y.DisplayName IN ([Column A], [Column B]) ) z;

{{1}}