Reputation: 2136
we are using sql server 2008 and data in below format.
and i want to above record in below pivot format.
please help.
Upvotes: 0
Views: 51
Reputation: 384
select * from PivotEx
pivot
(
avg(avg)
for city in ( [Mumbai] ,[Ahmedabad],[Raikot])
) piv;
To pass the values dynamically in pivot
Declare @cols nvarchar(max)
Declare @query nvarchar(max)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(city)
FROM PivotEx
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = ' select * from PivotEx
pivot
(
avg(avg)
for city in (' + @cols + ')
) p '
execute(@query)
Upvotes: 1