Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Concatenar valores de várias colunas no Oracle


SQL Fiddle

Configuração do esquema Oracle 11g R2 :
CREATE TABLE test (col1, col2, col3, col4, col5 ) AS
          SELECT 1, 'A', 'B', 'C', 'D' FROM DUAL
UNION ALL SELECT 2, 'A', 'B', 'C', NULL FROM DUAL
UNION ALL SELECT 3, 'C', 'A', NULL, NULL FROM DUAL
UNION ALL SELECT 4, 'D', 'A', 'C', NULL FROM DUAL
UNION ALL SELECT 5, NULL, NULL, NULL, NULL FROM DUAL
UNION ALL SELECT 6, NULL, NULL, NULL, 'A' FROM DUAL
UNION ALL SELECT 7, 'B', NULL, NULL, 'A' FROM DUAL
UNION ALL SELECT 8, NULL, 'C', NULL, 'A' FROM DUAL;

Consulta 1 :

Se não houver NULL valores entre outros valores (ele introduzirá várias vírgulas nas linhas 7 e 8):
SELECT col1,
       TRIM( ',' FROM col2||','||col3||','||col4||','||col5 ) AS col2
FROM   test

Resultados :
| COL1 |    COL2 |
|------|---------|
|    1 | A,B,C,D |
|    2 |   A,B,C |
|    3 |     C,A |
|    4 |   D,A,C |
|    5 |  (null) |
|    6 |       A |
|    7 |   B,,,A |
|    8 |    C,,A |

As duas últimas consultas funcionarão para todos os exemplos:

Consulta 2 :
SELECT col1,
       TRIM( ',' FROM col2 || NVL2( col3, ','||col3, NULL ) || NVL2( col4, ','||col4, NULL ) || NVL2( col5, ','||col5, NULL ) ) AS col2
FROM   test

Resultados :
| COL1 |    COL2 |
|------|---------|
|    1 | A,B,C,D |
|    2 |   A,B,C |
|    3 |     C,A |
|    4 |   D,A,C |
|    5 |  (null) |
|    6 |       A |
|    7 |     B,A |
|    8 |     C,A |

Consulta 3 :
SELECT col1,
       REGEXP_REPLACE( col2||','||col3||','||col4||','||col5, '(^|,),+|,+($)', '\1' ) AS col2
FROM   test

Resultados :
| COL1 |    COL2 |
|------|---------|
|    1 | A,B,C,D |
|    2 |   A,B,C |
|    3 |    C,A, |
|    4 |   D,A,C |
|    5 |  (null) |
|    6 |       A |
|    7 |     B,A |
|    8 |     C,A |