Oracle 11g R2 Schema-instellingen :
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;
Query 1 :
Als er geen NULL
. zijn waarden tussen andere waarden (het introduceert meerdere komma's in rijen 7 &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 |
De laatste twee zoekopdrachten werken voor alle voorbeelden:
Vraag 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 |
Vraag 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 |