unpivot with dynamic columns plus column names

吃可爱长大的小学妹 提交于 2019-11-26 11:37:20

问题


I\'m trying to unpivot a table with a large number of columns in the format of:

PID UID col1 col2 col3...

The dynamic SQL below will get me almost everything except the name of the column. The goal is to fill in the \"ID\" field with the name of the column from which the unpivot value originated.

-- Build list of cols we want to unpivot (skip PID & UID)
declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N\',\', N\'\') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = \'u\'
where o.name = \'MyTable\' and c.name not in (\'PID\', \'UID\') order by c.colid

declare @query nvarchar(max)  

select @query = N\'
select PID, [UID], ID, Val
from 
    (
    select PID, UID, \'\'ID\'\' as ID, \' + @cols + \'
    from MyTable
    where UID <> 0
    ) as cp
    unpivot
    (
    Val for Vals in (\' + @cols + \')
    ) as up
\'
exec sp_executesql @query 

I thought maybe I could do some sort of join with syscolumns & MyTable and then do a second unpivot but I haven\'t been able to figure it out.

Ultimately my query should return

PID UID ID          Val

123 456 \'col1 name\' \'xyz\'
123 456 \'col2 name\' \'def\'
123 333 \'col1 name\' \'fdf\'
...

So while I know how to get the name of the columns in order to generate the dynamic SQL for the unpivot, I don\'t know how to join the name of the columns into the output of the unpivot.


回答1:


You can reference the column name from the val for col in part of the unpivot. Col gets the column name

Example Fiddle

-- Build list of cols we want to unpivot (skip PID & UID)
declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = 'MyTable' and c.name not in ('PID', 'UID') order by c.colid

declare @query nvarchar(max)  

select @query = N'
select PID, [UID], Col as ID, Val
from 
    (
    select PID, UID, ' + @cols + '
    from MyTable
    where UID <> 0
    ) as cp
    unpivot
    (
    Val for Col in (' + @cols + ')
    ) as up
'
exec sp_executesql @query 


来源:https://stackoverflow.com/questions/18775409/unpivot-with-dynamic-columns-plus-column-names

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