简体   繁体   English

列名称未知的SQL Server 2008数据透视表

[英]SQL Server 2008 pivoting table with unknown column name

I am having trouble to pivot the following 我无法解决以下问题

    FirstName    LastName
    ----------------------
    Talyor       Swift
    Bruno        Mars

to the following 到以下

    ColumnName    ColumnValue
    --------------------------
    FirstName     Talyor
    LastName      Swift
    FirstName     Bruno
    LastName      Mars

I don't have any clue how to start this without hardcoding it especially the way to retrieve the column name from the system. 我不知道如何对它进行硬编码,特别是从系统中检索列名称的方法时,如何启动它。

**Column Name in the source table is not given **未提供源表中的列名

Here is a "dynamic" approach which is accomplished via XML. 这是一种通过XML完成的“动态”方法。

Clearly UNPIVOT would be more performant 显然,联波观察团的表现将更好

Example

Select C.*
      ,ColumnOrder = D.ORDINAL_POSITION
 From  YourTable A
 Cross Apply (Select XMLData = cast((Select A.* for XML Raw) as xml) ) B
 Cross Apply (
                Select Item   = attr.value('local-name(.)','varchar(100)')
                      ,Value  = attr.value('.','varchar(max)') 
                 From  B.XMLData.nodes('/row') as n(r)
                 Cross Apply n.r.nodes('./@*') AS B(attr)
             ) C
 Join INFORMATION_SCHEMA.COLUMNS D on D.Table_Name='YourTable' and D.Column_Name=C.Item

Returns 返回

Item        Value   ColumnOrder
FirstName   Talyor  1
LastName    Swift   2
FirstName   Bruno   1
LastName    Mars    2

EDIT - Dynamic UnPivot 编辑-动态取消旋转

Declare @SQL varchar(max) ='
Select ColumnOrder = D.ORDINAL_POSITION
      ,Item
      ,Value
 From  YourTable
 UnPivot (Value for Item in ('+Stuff((Select ',' +QuoteName(Name) 
                                       From  sys.columns 
                                       Where objecT_id = OBJECT_ID('YourTable') 
                                       For XML Path ('')),1,1,'')
                             +')) as UnPiv
 Join INFORMATION_SCHEMA.COLUMNS D on D.Table_Name=''YourTable'' and D.Column_Name=UnPiv.Item
'
--Print @SQL
Exec(@SQL)

From what I see in the question this should work: 从我在问题中看到的,这应该起作用:

select 'firstname', firstname from table
union all
select 'lastname', lastname from table

If the column names are not known you can select them from sys.columns table, make a sql string and use exec function to execute sql string. 如果列名未知,则可以从sys.columns表中选择它们,创建一个sql字符串,然后使用exec函数执行sql字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM