【问题标题】:Converting rows into Column in Oracle without any relationConverting rows into Column in Oracle without any relation
【发布时间】:2022-12-01 20:53:08
【问题描述】:

I have a query which will fetch two rows only and I want to bring second row data into columns with different column name.

Below is the original query result.

The expected result is like Expected result.

Please help how shd I proceed, not able to figure out with PIVOT.

【问题讨论】:

    标签: oracle oracle-sqldeveloper plsqldeveloper


    【解决方案1】:

    Here's one option; see cmets within code.

    SQL> with
      2  your_query (column1, column2, column3) as
      3    -- this is what your current query returns
      4    (select 1, 'ABC', 123 from dual union all
      5     select 2, 'XYZ', 456 from dual
      6    ),
      7  temp as
      8    -- distinguish 1st from 2nd row
      9    (select y.*,
     10            row_number() over (order by column1) rn
     11     from your_query y
     12    )
     13  -- finally, cross join two rows and conditionally display columns.
     14  -- MAX is here to avoid empty "cells"
     15  select max(case when a.rn = 1 then a.column1 end) as col1,
     16         max(case when a.rn = 1 then a.column2 end) as col2,
     17         max(case when a.rn = 1 then a.column3 end) as col3,
     18         --
     19         max(case when b.rn = 2 then b.column1 end) as col4,
     20         max(case when b.rn = 2 then b.column2 end) as col5,
     21         max(case when b.rn = 2 then b.column3 end) as col6
     22  from temp a cross join temp b;
    
          COL1 COL       COL3       COL4 COL       COL6
    ---------- --- ---------- ---------- --- ----------
             1 ABC        123          2 XYZ        456
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 2022-12-26
      • 2022-11-09
      • 2021-12-31
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2018-01-15
      相关资源
      最近更新 更多