안녕하세요
start with ~ connect by prior 구문에 대해 질문이 있습니다.
WITH T (HIGH_CATEGORY_ID, CATEGORY_ID, CATEGORY_NAME, CATEGORY_ORDER_NO) AS ( SELECT NULL , 'CT01', 'ROOT' , '1' FROM DUAL UNION ALL SELECT 'CT01', 'CT02', 'CATEGORY 1' , '1' FROM DUAL UNION ALL SELECT 'CT01', 'CT03', 'CATEGORY 2' , '2' FROM DUAL UNION ALL SELECT 'CT01', 'CT04', 'CATEGORY 3' , '3' FROM DUAL UNION ALL SELECT 'CT02', 'CT05', 'CATEGORY 1_SUB1', '1' FROM DUAL UNION ALL SELECT 'CT02', 'CT06', 'CATEGORY 1_SUB2', '2' FROM DUAL UNION ALL SELECT 'CT02', 'CT07', 'CATEGORY 1_SUB3', '3' FROM DUAL UNION ALL SELECT 'CT03', 'CT08', 'CATEGORY 2_SUB1', '1' FROM DUAL UNION ALL SELECT 'CT03', 'CT09', 'CATEGORY 2_SUB2', '2' FROM DUAL UNION ALL SELECT 'CT04', 'CT10', 'CATEGORY 3_SUB3', '1' FROM DUAL ) SELECT HIGH_CATEGORY_ID, CATEGORY_ID, LPAD(' ', (LEVEL-1)*4) || CATEGORY_NAME CATEGORY_NAME, CATEGORY_ORDER_NO FROM T START WITH T.HIGH_CATEGORY_ID IS NULL CONNECT BY PRIOR T.CATEGORY_ID = T.HIGH_CATEGORY_ID ORDER SIBLINGS BY T.CATEGORY_ORDER_NO
HIGH_CATEGORY_ID | CATEGORY_ID | CATEGORY_NAME | CATEGORY_ORDER_NO | |
1 | CT01 | ROOT | 1 | |
2 | CT01 | CT02 | CATEGORY 1 | 1 |
3 | CT02 | CT05 | CATEGORY 1_SUB1 | 1 |
4 | CT02 | CT06 | CATEGORY 1_SUB2 | 2 |
5 | CT02 | CT07 | CATEGORY 1_SUB3 | 3 |
6 | CT01 | CT03 | CATEGORY 2 | 2 |
7 | CT03 | CT08 | CATEGORY 2_SUB1 | 1 |
8 | CT03 | CT09 | CATEGORY 2_SUB2 | 2 |
9 | CT01 | CT04 | CATEGORY 3 | 3 |
10 | CT04 | CT10 | CATEGORY 3_SUB3 | 1 |
위와 같이 계층 구조를 가진 테이블에서 category_name 을 계층 구조로 정렬하여 출력할 수 있는데
이중에 특정 category_id 하위(자신포함) 일 경우에는 아래처럼 별도 컬럼값을 출력해 줄 수있는 방법이 있을까요?
*CATEGORY_ID 가 CT03 이거나 CT03하위의 정보에 TARGET_FLAG를 Y로 출력
HIGH_CATEGORY_ID | CATEGORY_ID | CATEGORY_NAME | CATEGORY_ORDER_NO | TARGET_FLAG | |
1 | CT01 | ROOT | 1 | ||
2 | CT01 | CT02 | CATEGORY 1 | 1 | |
3 | CT02 | CT05 | CATEGORY 1_SUB1 | 1 | |
4 | CT02 | CT06 | CATEGORY 1_SUB2 | 2 | |
5 | CT02 | CT07 | CATEGORY 1_SUB3 | 3 | |
6 | CT01 | CT03 | CATEGORY 2 | 2 | Y |
7 | CT03 | CT08 | CATEGORY 2_SUB1 | 1 | Y |
8 | CT03 | CT09 | CATEGORY 2_SUB2 | 2 | Y |
9 | CT01 | CT04 | CATEGORY 3 | 3 | |
10 | CT04 | CT10 | CATEGORY 3_SUB3 | 1 |
감사합니다.
SELECT HIGH_CATEGORY_ID, CATEGORY_ID, LPAD(' ', (LEVEL-1)*4) || CATEGORY_NAME CATEGORY_NAME, CATEGORY_ORDER_NO, CASE WHEN INSTR(SYS_CONNECT_BY_PATH(CATEGORY_ID,'-'),'CT03') > 0 THEN 'Y' END TARGET_FLAG FROM T START WITH T.HIGH_CATEGORY_ID IS NULL CONNECT BY PRIOR T.CATEGORY_ID = T.HIGH_CATEGORY_ID ORDER SIBLINGS BY T.CATEGORY_ORDER_NO