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

0

Please login or register to vote for this query.

(click on this box to dismiss)

Raspberry Pi Meta

Q&A about the site for users and developers of hardware and software for Raspberry Pi

CREATE table #yourtable
    ([Id] int, [Value] varchar(6), [ColumnName] varchar(13))
;
    
INSERT INTO #yourtable
    ([Id], [Value], [ColumnName])
VALUES
    (1, 'John', '2012'),
    (1, '2.4', '2012'),
    (3, 'ZH1E4A', '2011'),
    (4, 'Fork', '2010'),
    (3, '857685', '2011')
;


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