使用SQL将连接结果转换为两列

时间:2013-01-11 15:54:16

标签: sql unpivot

我有一个JOIN结果如下

Address1 Address2 Address3
ABC       XYZ      LMN

我想将它们转换为以下格式

Address    Level

ABC         1
XYZ         2
LMN         3

1 个答案:

答案 0 :(得分:3)

您需要UNPIVOTUNION ALL。这些将您的列转换为行。可以在所有RDBMS上完成UNION ALL

select address1 Address, 1 as level
from yourtable
union all
select address2 Address, 2 as level
from yourtable
union all
select address3 Address, 3 as level
from yourtable

请参阅SQL Fiddle with Demo

如果您使用的是带有UNPIVOT函数的RDBMS(SQL Server 2005 + / Oracle 11g +),那么您的查询将类似于:

select Address, 
  right(Level, 1) Level
from yourtable
unpivot
(
  address
  for level in (Address1, Address2, Address3)
) unpiv

请参阅SQL Fiddle with Demo

两者的结果是:

| ADDRESS | LEVEL |
-------------------
|     ABC |     1 |
|     XYZ |     2 |
|     LMN |     3 |