Joining multiple rows into a single row without aggregation [Oracle]

房东的猫 提交于 2021-01-29 21:30:17

问题


I have the following query:

select type,
       date,
       amount
  from table;

And it gives the following result:

TYPE    DATE        AMOUNT
--------------------------------
A       30.6.2019   15
B       30.11.2019  20
C       22.12.2019  17

What I want to do is write a query that would return the following:

TYPE1     DATE1      AMOUNT1     TYPE2    DATE2      AMOUNT2     TYPE3     DATE3      AMOUNT3
------------------------------------------------------------------------------------------------------
A         30.6.2019  15          B        30.11.2019 20          C         22.12.2019 17

The number of rows from the first query is always going to be 3 and not more than that. I can't concatenate because I need multiple columns in the final result set. Can this be done in Oracle SQL without using PL/SQL?


回答1:


If you know you have three columns, enumerate them and aggregate:

select max(case when seqnum = 1 then type end) as type1,
       max(case when seqnum = 1 then date end) as date1,
       max(case when seqnum = 1 then amount end) as amount1,
       max(case when seqnum = 2 then type end) as type2,
       max(case when seqnum = 2 then date end) as date2,
       max(case when seqnum = 2 then amount end) as amount2,
       max(case when seqnum = 3 then type end) as type3,
       max(case when seqnum = 3 then date end) as date3,
       max(case when seqnum = 3 then amount end) as amount3       
from (select t.*, rownum as seqnum
      from t
     ) t;

If you don't know the number of columns being returned, then you need to use dynamic SQL (execute immediate).



来源:https://stackoverflow.com/questions/59843323/joining-multiple-rows-into-a-single-row-without-aggregation-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!