我有一个 JOIN 结果如下
Address1 Address2 Address3
ABC XYZ LMN
我想将它们转换为以下格式
Address Level
ABC 1
XYZ 2
LMN 3
您将需要UNPIVOT
或UNION 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
如果您正在使用具有该UNPIVOT
功能的 RDBMS (SQL Server 2005+/Oracle 11g+),那么您的查询将类似于以下内容:
select Address,
right(Level, 1) Level
from yourtable
unpivot
(
address
for level in (Address1, Address2, Address3)
) unpiv
两者的结果是:
| ADDRESS | LEVEL |
-------------------
| ABC | 1 |
| XYZ | 2 |
| LMN | 3 |