0

我有一个Table1

ID Instance Name Size Tech
 1   0       D1  123   ABC
 1   1       D2  234   CDV
 2   2       D3  234   CDV
 2   3       D4  345   SDF

我需要使用 Dynamic 的结果集PIVOT与标题一起看起来像:

ID | Instance0_Name | Instance0_Size | Instance0_Tech | Instance1_Name | Instance1_Size | Instance1_tech
1  | D1             | 123            | ABC            | D2             | 234            | CDV

任何帮助,将不胜感激。使用 SQL Server 2008。

很抱歉之前的帖子。

4

1 回答 1

5

您想要的输出并不完全清楚,但您可以同时使用UNPIVOTandPIVOT函数来获得结果

如果您知道列数,那么您可以对这些值进行硬编码:

select *
from
(
  select id, 
    'Instance'+cast(instance as varchar(10))+'_'+col col, 
    value
  from 
  (
    select id, 
      Instance, 
      Name, 
      cast(Size as varchar(50)) Size,
      Tech
    from yourtable
  ) x
  unpivot
  (
    value
    for col in (Name, Size, Tech)
  ) u
) x1
pivot
(
  max(value) 
  for col in
    ([Instance0_Name], [Instance0_Size], [Instance0_Tech], 
     [Instance1_Name], [Instance1_Size], [Instance1_Tech], 
     [Instance2_Name], [Instance2_Size], [Instance2_Tech], 
     [Instance3_Name], [Instance3_Size], [Instance3_Tech])
) p

请参阅带有演示的 SQL Fiddle

然后如果你有未知数量的值,你可以使用动态sql:

DECLARE @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsPivot = STUFF((SELECT ',' 
                      + quotename('Instance'+ cast(instance as varchar(10))+'_'+c.name)
                    from yourtable t
                    cross apply sys.columns as C
                    where C.object_id = object_id('yourtable') and
                         C.name not in ('id', 'instance')
                    group by t.instance, c.name
                    order by t.instance
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
  = 'select *
      from
      (
        select id, 
          ''Instance''+cast(instance as varchar(10))+''_''+col col, 
          value
        from 
        (
          select id, 
            Instance, 
            Name, 
            cast(Size as varchar(50)) Size,
            Tech
          from yourtable
        ) x
        unpivot
        (
          value
          for col in (Name, Size, Tech)
        ) u 
      ) x1
      pivot
      (
        max(value)
        for col in ('+ @colspivot +')
      ) p'

exec(@query)

请参阅带有演示的 SQL Fiddle

如果结果不正确,请编辑您的 OP 并发布您期望从您提供的两个 ID 中获得的结果。

于 2013-01-08T21:51:13.760 回答