WITH t AS ( SELECT 1 pk, 'A' c1, 'B' c2, 'C' c3 FROM dual UNION ALL SELECT 2, 'A', 'C', 'B' FROM dual UNION ALL SELECT 3, 'D', 'B', 'C' FROM dual UNION ALL SELECT 4, 'E', 'D', 'A' FROM dual UNION ALL SELECT 5, 'X', 'Y', 'Z' FROM dual ) SELECT DISTINCT WM_CONCAT(DISTINCT DECODE(lv, 1, c1, 2, c2, 3, c3)) result FROM (SELECT DISTINCT c1, c2, c3 , CONNECT_BY_ROOT(pk) pk FROM t CONNECT BY NOCYCLE PRIOR c1 IN (c1, c2, c3) OR PRIOR c2 IN (c1, c2, c3) OR PRIOR c3 IN (c1, c2, c3) ) , (SELECT LEVEL lv FROM dual CONNECT BY LEVEL <= 3) GROUP BY pk ORDER BY result ;
WITH t AS ( SELECT 1 pk, 'A' c1, 'B' c2, 'C' c3 FROM dual UNION ALL SELECT 2, 'A', 'C', 'B' FROM dual UNION ALL SELECT 3, 'D', 'B', 'C' FROM dual UNION ALL SELECT 4, 'E', 'D', 'A' FROM dual UNION ALL SELECT 5, 'X', 'Y', 'Z' FROM dual ) SELECT DISTINCT SUBSTR(XMLAGG(XMLELEMENT(x, ',', x) ORDER BY x).EXTRACT('//text()'), 2) x FROM (SELECT DISTINCT pk , DECODE(lv, 1, c1, 2, c2, 3, c3) x FROM (SELECT DISTINCT c1, c2, c3 , CONNECT_BY_ROOT(pk) pk FROM t CONNECT BY NOCYCLE PRIOR c1 IN (c1, c2, c3) OR PRIOR c2 IN (c1, c2, c3) OR PRIOR c3 IN (c1, c2, c3) ) , (SELECT LEVEL lv FROM dual CONNECT BY LEVEL <= 3) ) GROUP BY pk ORDER BY x ;