Use the function PIVOT
to bring your rows in columns:
Example:
SELECT *
FROM (SELECT 1 codigo, 'Carro' nome FROM dual UNION ALL
SELECT 2 codigo, 'Moto' nome FROM dual UNION ALL
SELECT 3 codigo, 'Avião' nome FROM dual )
PIVOT
(
MAX(codigo) FOR nome IN ('Carro' Carro,'Moto' Moto,'Avião' Avião)
)
Upshot:
see rotating on SQL Fiddle.
More information on the subject can be found here.
A more advanced option would be to create a function that runs the SQL
dynamically and returns a CURSOR
, when you don’t know the values that can return...
Follow an example:
CREATE OR REPLACE FUNCTION fun_linhas_para_tabelas RETURN SYS_REFCURSOR IS
sqlqry CLOB;
cols CLOB;
TYPE t_ref_cursor IS REF CURSOR;
c t_ref_cursor;
BEGIN
SELECT listagg('''' || nome || ''' as "' || nome || '"', ',') within GROUP(ORDER BY nome)
INTO cols
FROM (SELECT 1 codigo, 'Carro' nome
FROM dual
UNION ALL
SELECT 2 codigo, 'Moto' nome
FROM dual
UNION ALL
SELECT 3 codigo, 'Avião' nome
FROM dual);
sqlqry := 'select * from
(
SELECT 1 codigo, ''Carro'' nome FROM dual UNION ALL
SELECT 2 codigo, ''Moto'' nome FROM dual UNION ALL
SELECT 3 codigo, ''Avião'' nome FROM dual
)
pivot
(
Max(codigo) for nome in (' || cols || ')
)';
OPEN c FOR sqlqry;
RETURN c;
END;
Try to explain better please
– Jakson Fischer
this search brings the following: CODPROD, PACKAGING 2 | 1X1 2 | 1X2 2 | 1X3
– Marcos Vinicius
Man, I’m sorry, but I’m not getting it... Try to literally draw or give a clearer example than you need, put it as part of the question please
– Jakson Fischer
From what I understand, you need to return an array, example:
Array[2]=> "1X1", "1X2", "1X3"
, in this way?– Jakson Fischer
I believe that yes, that it returns in a row only the results of others in columns
– Marcos Vinicius