CREATE TABLE #items ( part_number int, description varcha...

0

Please login or register to vote for this query.

(click on this box to dismiss)

Music Fans Meta

Q&A about the site for music historians, critics, and fans

CREATE TABLE #items (
  part_number int,
  description varchar(255)
);

INSERT INTO #items (part_number, description) VALUES 
(1, 'xxxxx'),
(1, 'yyyyy'),
(1, 'zzzzz'),
(2, 'aaaaa'),
(2, 'bbbbb'),
(2, 'ccccc');

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

select @cols = STUFF((SELECT ',' + QUOTENAME(part_number) 
                    from #items
                    group by part_number
                    order by part_number
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select description, part_number
                from #items
            ) x
            pivot 
            (
                max(description)
                for part_number  in (' + @cols + N')
            ) p '

exec sp_executesql @query;

Enter Parameters

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