Sql server 在SQL Server中将单行的列值转换为具有列标题的两列

Sql server 在SQL Server中将单行的列值转换为具有列标题的两列,sql-server,Sql Server,我需要将列和行转换为2列。 下面是示例表[Table01],共有4列和一行 First Second Third Forth 01 02 03 04 我需要将其转换为一个新表[Table01\u T] Column01 Column02 First 01 Second 02 Third 03 Forth 04 每次我们收到一行4列,我们需要它们转换成2列4行。类似这样的东西 sele

我需要将列和行转换为2列。 下面是示例表[Table01],共有4列和一行

First   Second  Third   Forth
01      02      03      04
我需要将其转换为一个新表[Table01\u T]

Column01     Column02
First         01
Second        02
Third         03
Forth         04
每次我们收到一行4列,我们需要它们转换成2列4行。

类似这样的东西

select
  v.*
from [Table01]
 cross apply
  (values ('First', [First]),('Second',[Second]),
          ('Third',[Third]),('Forth',[Forth])) v(Column01, Column02);
此查询使用相同的样本数据生成相同的结果。我发现这种语法比UNPIVOT更具可读性

结果

Column1 Column02
First   01
Second  02
Third   03
Forth   04

您可以使用
UNPIVOT

SELECT Column01, Column02
  -- INTO dbo.Table01_T
  FROM dbo.Table01 
  UNPIVOT 
    (                         -- vvvvv column names you want to turn to rows
      Column02 FOR Column01 IN ([First],[Second],[Third],[Fourth])
  --               ^^^^^^^^ becomes column name from each original column 
  --  ^^^^^^^^ becomes column value from each original column
    ) AS u;
使用表变量的单独示例:

DECLARE @x table([First] char(2),Second char(2),Third char(2),Fourth char(2));
INSERT @x([First],[Second],[Third],[Fourth]) VALUES ('01','02','03','04');

SELECT Column01, Column02
  FROM @x UNPIVOT 
  (
    Column02 FOR Column01 IN ([First],[Second],[Third],[Fourth])
  ) AS u;
结果:

Column01    Column02
--------    --------
First       01
Second      02
Third       03
Fourth      04

谢谢@AaronReadability当然是主观的。我更喜欢
UNPIVOT
,因为我觉得
'First',[First]
冗余且笨拙。:-)嗨@AaronBertrand,这个问题是关于这两种技术的一个很好的小全民公决!对我来说,交叉申请就像叠砖一样,很容易。使用UNPIVOT,我使用了很长时间,它总是涉及BOL。这绝对是主观的,tho:)干杯