Friday, April 24, 2015

Convert rows to columns

create table #TEST_RESULTS
(ID INT,NAME VARCHAR(10),DOB DATETIME,DAYS_SINCE_BIRTH_TO_TEST INT,TEST_RESULTS INT )

INSERT INTO #TEST_RESULTS
VALUES(1,'A','2015-01-01' , 0 ,1)
,(1,'A','2015-01-01' , 0 ,1)
,(1,'A','2015-01-01' , 1 ,3)
,(1,'A','2015-01-01' , 2 ,6)
,(1,'A','2015-01-01' , 2 ,9)
,(1,'A','2015-01-01' , 3 ,7)
,(1,'A','2015-01-01' , 5 ,12)
,(2,'B','2015-02-01' , 0 ,1)
,(2,'B','2015-02-01' , 4 ,3)
,(2,'B','2015-02-01' , 4,5)
,(2,'B','2015-02-01' , 3 ,8)

 SELECT ID,NAME,DOB,DAYS_SINCE_BIRTH_TO_TEST,AVG(CAST (TEST_RESULTS AS FLOAT)) AS AVG_TEST_RESULTS 
 into #A
 FROM #TEST_RESULTS 
 GROUP BY ID,NAME,DOB,DAYS_SINCE_BIRTH_TO_TEST 
 
 declare @List varchar(200)
 
select @List =
STUFF((Select distinct ','+quotename('Day_'+cast(DAYS_SINCE_BIRTH_TO_TEST as varchar(20)))
FROM #TEST_RESULTS 
FOR XML PATH('')),1,1,'')
declare @SQL nvarchar(2000)
set @SQL ='select * from 
(select ID,NAME,DOB,''Day_''+cast(DAYS_SINCE_BIRTH_TO_TEST as varchar(20)) as DAYS_SINCE_BIRTH_TO_TEST ,AVG_TEST_RESULTS from #A) PT PIVOT (MIN(AVG_TEST_RESULTS)  FOR DAYS_SINCE_BIRTH_TO_TEST in (' +@LIST+')) as PS' 

Execute SP_Executesql @SQL


Hope it Helps!!

No comments:

Post a Comment