sql >> Databasteknik >  >> RDS >> Sqlserver

Dynamiska pivotkolumner i SQL Server

Något så här:

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.

Detta ger dig något i stil med detta:

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



  1. Sekvens vs identitet

  2. Hur man pivoterar ett MySQL-entitet-attribut-värde-schema

  3. Service Broker-förbättringar i SQL Server 2016

  4. Så här ändrar du tabellkantstilen i psql-frågeresultaten