使用 SQL 服务器将列转换为行

Transpose Column to Rows using SQL Server

你能帮我一个案例吗,下面

我有一个原版table,像这样:


MONTH | YEAR | PO1 | PO2 | PO3

+++++++++++++++++++++++++++++++++++++++++

01      2010   100    20    10

那么我想要的结果是这样的:


DESCRIPTION | VALUE 
+++++++++++++++++++++++++++++++++++++++++
PO1            100
PO2             20
PO3             10

我应该如何在 SQL 服务器中执行此操作,非常感谢您的进步。

您可以使用 UNPIVOT 函数将列转换为行:

create table #test
(month int,year int,po1 int,po2 int ,po3 int)

insert into #test 
values
(5,2013,100,20,10)

select
  Description,
  value
from #test
unpivot
(
  value
  for Description in (po1, po2, po3)
) unpiv;

drop table #test

并取自@bluefeet answer 如果你有多列 unpivot 那么你可以使用 sql statement using dynamic SQL:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot 
  = stuff((select ','+quotename(C.column_name)
           from information_schema.columns as C
           where C.table_name = 'yourtable' and
                 C.column_name like 'PO%'
           for xml path('')), 1, 1, '')

set @query 
  = 'select 
       Description,
       value
     from yourtable
     unpivot
     (
        value
        for Description in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;