If you want to have a query that gives you a variable number of columns, a way could be dynamic SQL; for example, this query will build a query that does the job, no matter the number of records:
select
'select *
from
mapping
pivot ( max(code) for code in (' ||
listagg('''' || code || ''' AS column' || n, ',') within group (order by code) ||
'))'
from (select code, rownum n from mapping)
this gives this query:
select *
from
mapping
pivot ( max(code) for code in ('A' AS column1,'B' AS column2,'C' AS column3,'D' AS column4))
which gives:
COLUMN1 COLUMN2 COLUMN3 COLUMN4
------- ------- ------- -------
A B C D
1 row selected.
Now the issue is how would you use this; you can run a dynamic query with execute immediate
, but here you don't know in advance the number of columns, so you can not fetch the result of this query into anything.
A different approach could be by generating an XML result, for example:
select
dbms_xmlgen.getxml(
'select *
from
mapping
pivot ( max(code) for code in (' ||
listagg('''' || code || ''' AS column' || n, ',') within group (order by code) ||
'))'
)
gives:
<?xml version="1.0"?>
<ROWSET>
<ROW>
<COLUMN1>A</COLUMN1>
<COLUMN2>B</COLUMN2>
<COLUMN3>C</COLUMN3>
<COLUMN4>D</COLUMN4>
</ROW>
</ROWSET>
from (select code, rownum n from mapping)