SQL Server pivots? some way to set column names to

2019-04-09 11:22发布

问题:

I am building a system of multiple trackers that are going to use a lot of the same columns so there is a table for the trackers, the tracker columns, then a cross reference for which columns go with which tracker, when a user inserts a tracker row the different column values are stored in multiple rows that share the same record id and store both the value and the name of the particular column.

I need to find a way to dynamically change the column name of the value to be the column name that is stored in the same row.

i.e.

id | value | name
------------------
23 | red   | color
23 | fast  | speed

needs to look like this.

id | color | speed
------------------
23 | red   | fast

Any help is greatly appreciated, thank you.

回答1:

You can perform this type of query with a PIVOT. There are two ways, a static pivot where you hard-code the values of the columns or a dynamic pivot where the columns are determined at run-time.

Static Pivot (See SQL Fiddle with Demo)

select *
from 
(
  select id, value, name
  from test
) x
pivot
(
  min(value)
  for name in ([color], [speed])
) p

Dynamic Pivot (See SQL Fiddle with Demo)

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name) 
                    from test
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
      = 'SELECT id,' + @cols + ' from 
         (
            SELECT id, value, name
            FROM test
         ) x
         pivot 
         (
            min(value)
            for name in (' + @cols + ')
         ) p '

execute(@query)

Both queries will produce the same results. The difference is that in the first you have to code all of the values that you want to become columns.



回答2:

This is impossible. Column names are always static in SQL Server. You can generate dynamic SQL though.