Hi I am re-posting this as i have not been able to resolve my question.
I want to use a PIVOT script orig devleoped by Naomi.
The orig script allows for a pivot on a single column, where i need to pivot on more than 1 column
In my case a person can end up in Intensive care and have mulitple xRay's more than 100, so my data gives me this vertically.
I want to PIVOT on ID, xRay, xRayDate and really any other columns i desire.
In the following I have added DtXRay to this part of the code SET@SQL =COALESCE(@Sql+', ','')+'DtXray'+ cast(@iAS NVARCHAR(100)); So this gives me the column in the output but when i try to include this in the CTE it falls over
if anyone can help me that would be great.
CREATE TABLE tblTest ([InpatientEpisodeIdFk]INT ,[Field3]Varchar(50) ,[Field4]Varchar(50) ,[Field5]datetime ) INSERT INTO tblTest VALUES (617115,'General X-Ray','Chest X-Ray','2013-01-01 00:00:00.000' ), (617115,'General X-Ray','Femur X-ray (Right)','2013-01-01 00:00:00.000' ), (617115,'General X-Ray','Knee X-ray (Right)','2013-01-01 00:00:00.000' ), (617115,'General X-Ray','XR Pelvis & Right Hip','2013-01-01 00:00:00.000' ), (617115,'Computed Tomography','CT Brain','2013-01-01 00:00:00.000' ), (800895,'Computed Tomography','CT Brain Venogram (Contrast)','2013-01-01 00:00:00.000' ), (800895 ,'General X-Ray', 'Chest X-Ray', '2013-01-01 00:00:00.000' ), (800895,'Digital Angiography', 'DSA Chest XRay', '2013-01-02 00:00:00.000' )
DECLARE @MaxCount INT SELECT @MaxCount = max(cnt) FROM ( SELECT InpatientEpisodeIdFk ,count(Field3) as Cnt FROM tblTest Where InpatientEpisodeIdFk >0 GROUP BY InpatientEpisodeIdFk ) X; DECLARE @SQL NVARCHAR(max) ,@i INT; SET @i = 0; WHILE @i < @MaxCount BEGIN SET @i = @i + 1; SET @SQL = COALESCE(@Sql + ', ', '') + 'xRay' + cast(@i AS NVARCHAR(100)); SET @SQL = COALESCE(@Sql + ', ', '') + 'DtXray' + cast(@i AS NVARCHAR(100)); END SET @SQL = N' ;WITH CTE AS ( SELECT InpatientEpisodeIdFk, Field4, ''xRay'' + CAST(row_number() OVER (PARTITION BY InpatientEpisodeIdFk ORDER BY Field3) AS Varchar(155)) AS RowNo FROM tblTest ) SELECT * FROM CTE PIVOT (MAX(Field4)FOR RowNo IN (' + @SQL + N')) AS pvt1' ; PRINT @SQL; EXECUTE (@SQL);
David