在t-SQL中进入列?

时间:2016-01-11 10:47:43

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

我有一张这样的表:

ID  ColumnName
1   START_DTTM
1   END_DTTM
1   STATUS
2   START_DTTM
2   END_DTTM
2   status
3   START_DTTM
3   END_DTTM
3   status
3   Archive

我想要这样的结果:

ID  ColumnName      ColumnName2     ColumnName3     ColumnName4 
1   START_DTTM      END_DTTM        status          NULL
2   START_DTTM      END_DTTM        status          NULL
3   START_DTTM      END_DTTM        status          Archive

任何帮助..谢谢提前

1 个答案:

答案 0 :(得分:4)

这会产生想要的结果。但请注意,没有隐式排序顺序!如果没有特定的ORDER BY,您可能会得到随机结果。

declare @tbl TABLE(ID INT,  ColumnName VARCHAR(100));
INSERT INTO @tbl VALUES
 (1,'START_DTTM')
,(1,'END_DTTM')
,(1,'STATUS')
,(2,'START_DTTM')
,(2,'END_DTTM')
,(2,'status')
,(3,'START_DTTM')
,(3,'END_DTTM')
,(3,'status')
,(3,'Archive');


SELECT p.*
FROM
(
    SELECT 'ColumnName' + CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS VARCHAR(10)) AS PivotColumn
          ,tbl.*
    FROM @tbl AS tbl
) AS x
PIVOT
(
    MIN(ColumnName) FOR PivotColumn IN(ColumnName1,ColumnName2,ColumnName3,ColumnName4)
) AS p

结果:

ID  ColumnName1 ColumnName2 ColumnName3 ColumnName4
1   START_DTTM  END_DTTM    STATUS      NULL
2   START_DTTM  END_DTTM    status      NULL
3   START_DTTM  END_DTTM    status      Archive