start with ~ connect by 구문 문의 드립니다. 0 2 2,011

by 박군two [SQL Query] [2017.08.10 11:58:42]


안녕하세요 

 

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  

감사합니다.

by jkson [2017.08.10 12:15:27]
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

 


by 박군two [2017.08.10 14:04:19]

악.. 감사합니다.

구글링 해 봤던건데 .. 생각이 안났네요.. 

감사합니다.

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입