我怎样才能将列UNPIVOT分成行?

时间:2014-07-09 10:03:54

标签: sql sql-server sql-server-2008

考虑下表#document_fields

id   x   y    z
------------------
1  foo  bar  baz
2  one  two  three
3  aaa  bbb  ccc
4  123  456  789

列数可能会有所不同,列名也是如此。我需要将列转换为如下行:

id  field value
---------------
1   x     foo
1   y     bar
1   z     baz
2   x     one
2   y     two
2   z     three
.
.
3   z     789

我试图了解SQL Server中的数据透视方式是如何工作的,但除此之外还不能做到:

select 
      *
into
      #document_fields_pivot
from (
      select * from (
            select *
            from #document_fields
      ) t
      pivot (
            -- ??
      ) p
  ) tbl

任何人都可以帮我完成这个查询/解释我的转动吗?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

你想要的是UNPIVOT,并且这样做:

select id,field,value from
#document_fields
unpivot
(
 value
 for field in (x,y,z)
) as u
order by id,field

Demo

答案 1 :(得分:1)

DECLARE @Component table (ComponentId INT,Descr VARCHAR(10),Descr1 VARCHAR(10),Descr2 VARCHAR(10))
INSERT INTO @Component (ComponentId,Descr,Descr1,Descr2)values (1,'foo','bar','baz')
INSERT INTO @Component (ComponentId,Descr,Descr1,Descr2)values (2,'one','two','three')
INSERT INTO @Component (ComponentId,Descr,Descr1,Descr2)values (3,'aaa','bbb','ccc')
INSERT INTO @Component (ComponentId,Descr,Descr1,Descr2)values (3,'123','456','789')


   select
      ComponentId,Field
   from @Component P

 UNPIVOT
 (
   Field
   FOR Value
   IN (
    [Descr],[Descr1],[Descr2]
   )
 ) PivotTable;