Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Dynamische Pivot-Spalten in SQL Server

Etwa so:

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

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

SELECT @query =

'SELECT *
FROM
(
  SELECT
    o.object_id,
    p.Name,
    o.value
  FROM propertyObjects AS o
  INNER JOIN property AS p ON o.Property_Id = p.Id
) AS t
PIVOT 
(
  MAX(value) 
  FOR Name IN( ' + @cols + ' )' +
' ) AS p ; ';

 execute(@query);

SQL-Fiddle-Demo.

Dadurch erhalten Sie etwa Folgendes:

| OBJECT_ID | PROPERTY1 | PROPERTY2 | PROPERTY3 | PROPERTY4 |
-------------------------------------------------------------
|         1 |        ee |        fd |       fdf |      ewre |
|         2 |       dsd |       sss |      dfew |       dff |