我有下表,并希望将行转换为不同的列

时间:2010-07-01 13:01:47

标签: sql-server-2005

ID    Code      Date
1     3101       10/2/2010
1     3101       15/2/2010
2     3101       18/2/2010
2     3101       25/4/2010
2     3101       21/4/2010 

进入以下

ID   Date1      Date2      Date3       Date4      Date5
 1   10/2/2010  15/2/2010  
 2   18/2/2010  25/4/2010  21/4/2010  

1 个答案:

答案 0 :(得分:4)

您可以使用PIVOT。示例如下:

CREATE TABLE #Data
(
    ID INT NOT NULL,
    Code INT NOT NULL,
    [Date] VARCHAR(20) NOT NULL
)
INSERT INTO #Data VALUES(1, 3101, '10-2-2010')
INSERT INTO #Data VALUES(1, 3101, '15-2-2010')
INSERT INTO #Data VALUES(2, 3101, '18-2-2010')
INSERT INTO #Data VALUES(2, 3101, '25-4-2010')
INSERT INTO #Data VALUES(2, 3101, '21-4-2010')

SELECT ID, [1] AS Date1, [2] AS Date2, [3] AS Date3, [4] AS Date4
FROM
(SELECT ID, [Date], ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) [RowNum]
 FROM #Data) AS p
PIVOT (Max([Date]) FOR [RowNum] IN ([1],[2],[3],[4])) AS pvt

假设您需要更多日期,只需添加更多枢轴行即可。