0

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?

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
jcrudess
  • 1
  • 1

1 Answers1

0

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).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786