SQL Server pivots? some way to set column names to values within a row

爱⌒轻易说出口 提交于 2019-12-21 17:52:38

问题


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.



来源:https://stackoverflow.com/questions/11300428/sql-server-pivots-some-way-to-set-column-names-to-values-within-a-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!