Configuración del esquema de 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 :
Si no hay NULL
valores entre otros valores (introducirá varias comas en las filas 7 y 8):
SELECT col1,
TRIM( ',' FROM col2||','||col3||','||col4||','||col5 ) AS col2
FROM test
| 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 |
Las dos últimas consultas funcionarán para todos los ejemplos:
Consulta 2 :
SELECT col1,
TRIM( ',' FROM col2 || NVL2( col3, ','||col3, NULL ) || NVL2( col4, ','||col4, NULL ) || NVL2( col5, ','||col5, NULL ) ) AS col2
FROM test
| 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
| 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 |