Share

PIVOT TABLE - SQL


Dynamic pivot in SQL server

DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX)


select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)

from yourtable

group by ColumnName, id

order by id

FOR XML PATH(''), TYPE

).value('.', 'NVARCHAR(MAX)')

,1,1,'')


set @query = 'SELECT ' + @cols + ' from

(

select value, ColumnName

from your table

) x

pivot

(

max(value)

for ColumnName in (' + @cols + ')

) p '


1