3

我有一个 JOIN 结果如下

Address1 Address2 Address3
ABC       XYZ      LMN

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

Address    Level

ABC         1
XYZ         2
LMN         3
4

1 回答 1

3

您将需要UNPIVOTUNION ALL。这些获取您的列并将其转换为行。AUNION ALL可以在所有 RDBMS 上完成:

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

如果您正在使用具有该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

两者的结果是:

| ADDRESS | LEVEL |
-------------------
|     ABC |     1 |
|     XYZ |     2 |
|     LMN |     3 |
于 2013-01-11T15:55:27.597 回答