【问题标题】:unpivot with dynamic columns plus column names使用动态列加上列名取消透视
【发布时间】: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


【解决方案1】:

您可以从 unpivot 的 val for col in 部分引用列名。 col 获取列名

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 

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多