J R B
J R B

Reputation: 2136

record in pivot format in sql server

we are using sql server 2008 and data in below format.

enter image description here

and i want to above record in below pivot format. enter image description here

please help.

Upvotes: 0

Views: 51

Answers (1)

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

Related Questions