create table PivotTable (Date varchar(10), Location varchar(2), observation varchar(20))
insert into PivotTable
select '25/6/2009', 'A1', 'HI'
union all select '25/6/2009', 'A2', 'Nil'
union all select '25/6/2009', 'A1', 'Xxx'
union all select '25/6/2009', 'A2', 'Yyy'
union all select '25/6/2009', 'A1', 'AAA'
union all select '25/6/2009', 'A3', '3AA'
union all select '25/6/2009', 'A3', '3VB'
union all select '22/6/2009', 'A4', '4AA'
union all select '22/6/2009', 'A4', '4VB'
declare @Locations nvarchar(max)
declare @LocationValues nvarchar(max)
declare @sql nvarchar(max)
set @Locations = stuff((select distinct ',[' + Location +']' from PivotTable for xml path('')),1,1,'')
set @LocationValues = stuff((select distinct ',coalesce([' + Location +'],'''') as ' + Location from PivotTable for xml path('')),1,1,'')
set @sql = 'select Date,' + @LocationValues + ' from (select *,row_number() over (partition by Date,Location order by Date) as rn from Pivottable) p
pivot (max(observation) for Location in (' + @Locations + '))pvt'
exec(@sql)
Give a man a fish and you feed him for a day. Teach a man to fish and you feed him forever.