요구사항이 그러하니 어쩔수 없다는 건가요?
저는 왜 그런 요구를 했는지 그 이유가 궁금합니다.
합당한 이유가 아니라면 설득하고 대안을 제시할 수 있어야 합니다.
WITH t AS ( SELECT '1' cd, '' pcd FROM dual UNION ALL SELECT '2' , '1' FROM dual UNION ALL SELECT '2a', '2' FROM dual UNION ALL SELECT '2b', '2' FROM dual UNION ALL SELECT '3' , '1' FROM dual UNION ALL SELECT '3a', '3' FROM dual UNION ALL SELECT '3b', '3' FROM dual UNION ALL SELECT '4' , '1' FROM dual UNION ALL SELECT '4a', '4' FROM dual UNION ALL SELECT '4c', '4a' FROM dual UNION ALL SELECT '4b', '4' FROM dual ) -- 1. 내가 생각하는 정답(추천) -- SELECT * FROM (SELECT DISTINCT cd, pcd FROM t START WITH INSTR(cd, 'a') > 0 CONNECT BY cd = PRIOR pcd UNION ALL SELECT cd, pcd FROM t START WITH INSTR(pcd, 'a') > 0 CONNECT BY PRIOR cd = pcd ) START WITH pcd IS NULL CONNECT BY PRIOR cd = pcd ; -- 2. Distnct 와 Union 을 사용하지 않고 구현(비추) -- SELECT * FROM (SELECT * FROM t a WHERE EXISTS (SELECT 1 FROM t WHERE INSTR(cd, 'a') > 0 START WITH cd = a.cd CONNECT BY PRIOR cd = pcd ) OR EXISTS (SELECT 1 FROM t WHERE INSTR(cd, 'a') > 0 START WITH cd = a.cd CONNECT BY cd = PRIOR pcd ) ) START WITH pcd IS NULL CONNECT BY PRIOR cd = pcd ;