views:

35

answers:

1
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  
+4  A: 

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.

Ronald Wildenberg
SELECT ID, [Date1],[Date2],[Date3],[Date4] FROM (SELECT ID, Date FROM #tempAMS) p PIVOT (Max(Date)FOR Date IN ([Date1],[Date2],[Date3],[Date4]))AS pvtThis is my attempt at a pivotand itdoesnt seemto work - Icant get the dates into the relevant columns
Caroline Briggs
I was trying originally to use a cursor as I aslo will have other codes to go into other date columns so I can calculate the numberof days paused per id but that wouldnt do it for me either - I am new to TSQL and have only been using it a couple of months
Caroline Briggs
I'm also trying to get this to work but it seems I'm not that good in pivoting data after all.. I'll keep trying..
Ronald Wildenberg
@Ronald: This is a very useful method of pivoting. Great use of row_number! +1
Kenneth
Wonderful I will go and transfer this into my database Thanks
Caroline Briggs
You're welcome :) Could you please mark the question as answered?
Ronald Wildenberg