sql >> Base de Datos >  >> RDS >> Oracle

Transponer resultados seleccionados con Oracle

Si desea generar la consulta para cada llamada o usar un número máximo de columnas codificadas, entonces puede hacer algo así:

WITH tab AS
(
  SELECT table_name, column_name FROM user_tab_cols WHERE column_id <= 4
) -- user_tab_cols used to provide test data, use your table instead
SELECT MAX(c1) c1,
       MAX(c2) c2,
       MAX(c3) c3,
       MAX(c4) c4
  FROM (SELECT table_name,
               DECODE( column_id, 1, column_name ) c1,
               DECODE( column_id, 2, column_name ) c2,
               DECODE( column_id, 3, column_name ) c3,
               DECODE( column_id, 4, column_name ) c4
          FROM ( SELECT table_name,
                        column_name,
                        ROW_NUMBER() OVER ( PARTITION BY table_name ORDER BY column_name ) column_id
                   FROM tab
               )
       )
 GROUP BY table_name
 ORDER BY table_name

Si es suficiente para obtenerlo en esa forma

TABLENAME1|COL1,COL2
TABLENAME2|COL1,COL2,COL3

echa un vistazo al stragg de Tom Kyte.