CREATE table #yourtable ([Id] varchar(6) , [Value] varcha...

0

Please login or register to vote for this query.

(click on this box to dismiss)

Ask Ubuntu

Q&A for Ubuntu users and developers

CREATE table #yourtable
([Id] varchar(6) , [Value] varchar(6), [ColumnName] varchar(13))
;
    
INSERT INTO #yourtable
    ([Id], [Value], [ColumnName])
VALUES
    ('ABC', 'John', 'dev'),
    ('ABC', '2.4', 'test'),
    ('ABC', 'ZH1E4A', 't1'),
    ('ABC', 'Fork', 't2'),
    ('ABC', '857685', 't3')
;


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;

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results