If the values of date are unknown, you may need a dynamic sql solution. Here's you you do it:create table #t (Id int, Date date, Patient varchar(20), blood int, Urine int, Cholesterol int)insert into #t(ID, date, patient, blood, Cholesterol, Urine) values(123 ,'2014-01-15','john', 123 ,12,33),(123 ,'2014-07-11','john', 456 ,11,34),(123 ,'2014-09-01','john', 22 ,11,31)declare @cols nvarchar(max);set @cols = stuff(( select ','+quotename(date) from #t order by date for xml path('') ),1,1,'')--select @colsdeclare @sql nvarchar(max) = N' select measure, ' + @cols +' from (select ''blood'' as measure, date, blood from #t)src ' +' pivot(sum(blood) for date in (' + @cols + '))pvt' +' union all ' +' select measure, ' + @cols +' from (select ''urine'' as measure,date, Urine from #t)src ' +' pivot(sum(Urine) for date in (' + @cols + '))pvt' +' union all ' +' select measure, ' + @cols +' from (select ''chloresterol'' as measure,date, Cholesterol from #t)src ' +' pivot(sum(Cholesterol) for date in (' + @cols + '))pvt' print @sqlexec ( @sql)
Note that you need multiple pivots since you have multiple measures. Also, this may not run as fast as you like on large tables. YMMV