开发者

I have the following table and want to turn the rows into different columns

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 

into the following

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


You can use PIVOT for this. Example below:

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

Suppose you need more dates, it is just a matter of adding more pivot rows.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜