EDUDOTNET

Wednesday, December 16, 2015

How Design A SQL Query With Dynamic Pivot Columns in SQL Server

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Id)
                      FROM RWX_Users FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

SELECT @query =
'SELECT *
FROM
(
  SELECT
    Users.Id
  FROM RWX_Users AS Users
) AS t
PIVOT 
(
  MAX(Id) 
  FOR Id IN( ' + @cols + ' )' +
') AS p ; ';

execute(@query);

0 comments:

Post a Comment