I need to dynamically transform data in table #table from this format:
spot_id name pct ------- ---- --- 1 A 2 1 B 8 1 C 6 2 A 4 2 B 5 3 A 5 3 D 1 3 E 4
to:
spot_id A B C D E ------- --- --- --- --- --- 1 2 5 6 0 0 2 4 5 0 0 0 3 5 0 0 1 4
The thing is that I don't know in advance what the values of column "name" are or how many of them there are, so I think that I have to use some kind of dynamic SQL pivoting
Just figured out how to solve the problem:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(name) 
                    from (SELECT DISTINCT name FROM #table) T
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = N'SELECT spot_id,' + @cols + N' from 
             (
                select spot_id, name, pct
                from #table
            ) as x
            pivot 
            (
                max(pct)
                for name in (' + @cols + N')
            ) as p '
exec sp_executesql @query;
If there more elegant way to do the same?
                        
Using Dynamic Query :