【问题标题】:Transform Rows into Columns Oracle SQL [duplicate]将行转换为列 Oracle SQL [重复]
【发布时间】:2020-02-23 13:00:25
【问题描述】:

有没有像这样快速转换表格的方法:

FIELD   |  VALUE
+-------+----------+
Address |  here
Name    |  Rainer
Tel     |  01234567
Other   |  idk

进入这个:

Address | Name     | Tel     | Other
+-------+----------+---------+----------+
here    |  Rainer  | 01234567| idk

【问题讨论】:

    标签: sql oracle pivot


    【解决方案1】:

    你也可以使用pivot方法:

    select * 
      from tab
     pivot(
           max(value) for field in ( 'Address' as "Address", 
                                     'Name'    as "Name", 
                                     'Tel'     as "Tel", 
                                     'Other'   as "Other" ) ) 
    

    Demo

    【讨论】:

    • 您不需要嵌套子查询。你可以做SELECT * FROM tab PIVOT ...
    • 是的,谢谢@MT0。
    • 欢迎你@DropMania
    【解决方案2】:

    使用条件聚合:

    select
        max(case when field = 'Address' then value end) Address,
        max(case when field = 'Name' then value end) Name
        max(case when field = 'Tel' then value end) Tel
        max(case when field = 'Other' then value end) Other
    from mytable
    

    在正常情况下,您需要一个指向group by 的列,例如一个用户ID,这样您就可以从初始内容中生成多条记录。

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多