如何在 Oracle 中的文本数据下方进行透视?

How to pivot below Text data in Oracle?

*Input Table : 如何将数据从两个不同的列获取到 oracle 中的一个列中。

name   age   city    state
 A      25    CAL     WB
 B      27    PAT     BR
 B      38    HOW     WB

*输出Table

 name   age   place
  A      25     CAL
  A      25     WB
  B      27     PAT
  B      27     BR
  B      38     HOW
  B      38     WB

您可以使用 union all :

select name, age, city as place
from t 
union all
select name, age, state as place
from t;

UNPIVOT 子句非常适合该目的。

with t (name, age, city, state) as (
select 'A', 25, 'CAL', 'WB' from dual union all
select 'B', 27, 'PAT', 'BR' from dual union all
select 'B', 38, 'HOW', 'WB' from dual
)
select name, age, place, type
from t
unpivot (
place for type in (
  city as 'city'
, state as 'state' 
  )
)
;

你可以使用横向连接:

select t.name, age, x.place
from input t cross join lateral
     (select t.city as place from dual union all
      select t.state as place from dual
     ) x;

我还认为 unpivoting 提供了对横向连接的一个很好的温和介绍,它在许多其他上下文中非常强大和有用(与不是很通用的 unpivot 语法相反)。