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) --to get even missing numbers select @List = STUFF((select distinct ','+quotename('Day_'+cast(b.number as varchar(20))) from (select max(Days_Since_Birth_to_test) as number FROM #TEST_RESULTS)A INNER JOIN master..spt_values B on A.number>=B.number where type= 'p' 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