尝试旋转 T-SQL 中的多列

Trying to pivot multiple columns in T-SQL

我有一个动态生成不同行数的查询,具有不同的 ID 列值。我需要能够将其 PIVOT 为柱状结果。我目前的数据结果如下。

ID    Caption    FieldName     FieldType
---   ---------  ------------  ------------ 
10    Caption 1  Field Name 1  Field Type 1 
11    Caption 2  Field Name 2  Field Type 2 
12    Caption 3  Field Name 3  Field Type 3 
20    Caption 4  Field Name 4  Field Type 4 
30    Caption 5  Field Name 5  Field Type 5

我想要的结果是

10            11            12            20            30
--------      ----------    ---------     ---------     --------- 
Caption 1     Caption 2     Caption 3     Caption 4     Caption 5
Field Name 1  Field Name 2  Field Name 3  Field Name 4  Field Name 5
Field Type 1  Field Type 2  Field Type 3  Field Type 4  Field Type 5

请注意,值 10、11、12、20 和 30 可以更改为其他值,因此我知道我需要做一些动态 sql。我想尽可能避免使用 CURSORS。

欢迎提出任何建议。请原谅格式

如果你不介意动态化

我对删除 SEQ(结果的第一列)犹豫不决。您可以从最终查询中删除 [SEQ],,但我不确定它是否会在更大的数据集上保持正确的顺序。

Declare @SQL varchar(max) 
Select  @SQL = Stuff((Select Distinct ',' + QuoteName(ID) From YourTable Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
 Select [Seq],' + @SQL + '
  From (
        Select Item=A.ID,B.* 
         From  YourTable A
         Cross Apply (
                       Select Seq=1,Value=cast(A.Caption   as varchar(max)) Union All
                       Select Seq=2,Value=cast(A.FieldName as varchar(max)) Union All
                       Select Seq=3,Value=cast(A.FieldType as varchar(max))
                     ) B
       ) A
 Pivot (max(value) For Item in (' + @SQL + ') ) p'
Exec(@SQL);

Returns

EDIT - With SEQ Removed from the final Select

2005 Version

Declare @SQL varchar(max) 
Select  @SQL = stuff((Select Distinct ',' + QuoteName(ID)+'=max(case when Item='+cast(ID as varchar(25))+' then Value else null end)' From  YourTable Order By 1 For XML Path('') ),1,1,'')
Select  @SQL = '
 Select [Seq],'+@SQL +'
 From   (
         Select Item=A.ID,B.* 
         From  YourTable A
         Cross Apply ( 
                       Select Seq=1,Value=cast(A.Caption   as varchar(max))  Union All
                       Select Seq=2,Value=cast(A.FieldName as varchar(max))  Union All
                       Select Seq=3,Value=cast(A.FieldType as varchar(max))
                      ) B
        ) A
Group By Seq
Order By Seq
'
Exec(@SQL);

Returns