Q&A for practitioners, researchers, and students in cognitive science, psychology, neuroscience, and psychiatry
CREATE table #yourtable ([Id] int, [Value] varchar(6), [ColumnName] varchar(13)) ; INSERT INTO #yourtable ([Id], [Value], [ColumnName]) VALUES (1, 'John', 'FirstName'), (2, '2.4', 'Amount'), (3, 'ZH1E4A', 'PostalCode'), (4, 'Fork', 'LastName'), (5, '857685', 'AccountNumber'), (1, 'mani', 'FirstName'), (2, '2.3', 'Amount'), (3, 'ZE4A', 'PostalCode'), (4, 'Foio', 'LastName'), (5, '857764', 'AccountNumber') ; 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 = N'SELECT ' + @cols + N' from ( select value, ColumnName from #yourtable ) x pivot ( max(value) for ColumnName in (' + @cols + N') ) p ' exec sp_executesql @query;