【发布时间】:2013-09-17 11:56:34
【问题描述】:
我正在尝试对包含大量列的表格进行反透视,格式如下:
PID UID col1 col2 col3...
下面的动态 SQL 将得到我几乎所有的东西,除了列的名称。目标是在“ID”字段中填写 unpivot 值源自的列的名称。
-- 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
我想也许我可以使用 syscolumns 和 MyTable 进行某种形式的联接,然后进行第二次反透视,但我无法弄清楚。
最终我的查询应该返回
PID UID ID Val
123 456 'col1 name' 'xyz'
123 456 'col2 name' 'def'
123 333 'col1 name' 'fdf'
...
因此,虽然我知道如何获取列的名称以便为 unpivot 生成动态 SQL,但我不知道如何将列的名称连接到 unpivot 的输出中。
【问题讨论】:
-
我想你可以把
Vals当作一个列 -
添加了一些示例输出以显示列名需要如何替换 ID 占位符。
标签: sql sql-server-2005 dynamic unpivot