【问题标题】:How to pivot below Text data in Oracle? [duplicate]如何在 Oracle 中的文本数据下方进行旋转? [复制]
【发布时间】:2026-01-27 00:15:02
【问题描述】:

*Input Table : 如何在 oracle 中从两个 diff 列中获取数据到一列中。

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

*输出表

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

【问题讨论】:

  • 既然你知道它是(un)pivot,那么到目前为止你尝试了什么,它有什么问题?你的研究结果是什么?
  • 所有的例子和场景都是使用一些数字聚合来解释的,我想使用所有文本数据进行透视(我在这部分卡住了)

标签: sql oracle pivot-table


【解决方案1】:

你可以使用横向连接:

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;

我还认为反透视为横向联接提供了一个很好的温和介绍,横向联接在许多其他情况下非常强大和有用(与不太通用的 unpivot 语法相反)。

【讨论】:

    【解决方案2】:

    你可以使用union all

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

    【讨论】:

    • 嗨,yogesh,你能告诉我为什么在这个例子中使用Union all而不是Union吗?
    【解决方案3】:

    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' 
      )
    )
    ;
    

    【讨论】:

      最近更新 更多