试图在T-SQL中转动多个列

时间:2016-12-08 21:19:03

标签: sql-server tsql sql-server-2005

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

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。

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

2 个答案:

答案 0 :(得分:0)

如果你不介意动态

我对删除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);

返回

enter image description here

  

编辑 - 使用SEQ从最终选择中删除

enter image description here

答案 1 :(得分:0)

  

2005版本

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);

返回

enter image description here