-- Oracle
EMP 表里存在 父子关系 (ID & PARENT_ID)
ENAME MGR
---------- ----------
SCOTT JONES
ADAMS SCOTT
SQL:
SELECT ename ,PRIOR ename mgr FROM emp WHERE 1 = 1 AND 'SCOTT' IN (ename, PRIOR ename) START WITH mgr IS NULL CONNECT BY PRIOR empno = mgr
在EMP TREE结构里 如何求 leaf node 的总个数?
SQL:
SELECT SUM (leaf_flag) leaf_cnt FROM (SELECT (CASE WHEN LEVEL >= LEAD (LEVEL, 1, LEVEL) OVER (ORDER BY 1) THEN 1 END) leaf_flag FROM emp START WITH mgr IS NULL CONNECT BY PRIOR empno = mgr)
在TREE结构里怎么把 子节点的数据显示在夫节点?
WITH T AS ( SELECT '1'MENU_ID,'0' P_MENU_ID,'A' NAME,0 AMT FROM DUAL UNION ALL SELECT '2'MENU_ID,'1' P_MENU_ID,'B' NAME,20 AMT FROM DUAL UNION ALL SELECT '3'MENU_ID,'2' P_MENU_ID,'C' NAME,30 AMT FROM DUAL UNION ALL SELECT '4'MENU_ID,'2' P_MENU_ID,'D' NAME,40 AMT FROM DUAL UNION ALL SELECT '5'MENU_ID,'1' P_MENU_ID,'E' NAME,50 AMT FROM DUAL UNION ALL SELECT '6'MENU_ID,'5' P_MENU_ID,'F' NAME,60 AMT FROM DUAL UNION ALL SELECT '7'MENU_ID,'6' P_MENU_ID,'G' NAME,70 AMT FROM DUAL )
想要的结果?
NAME AMT AMT_CHILD
---- --- ---------
A 0 270
B 20 90
C 30 30
D 40 40
E 50 180
F 60 130
G 70 70
SQL:
SELECT NAME ,amt , (SELECT SUM (CASE WHEN SYS_CONNECT_BY_PATH (menu_id, ',') || ',' LIKE '%,' || a.menu_id || ',%' THEN amt END) FROM t START WITH p_menu_id = 0 CONNECT BY PRIOR menu_id = p_menu_id) amt_child FROM t a
或者 更简洁
SELECT NAME ,amt , (SELECT SUM (amt) FROM t START WITH menu_id = a.menu_id CONNECT BY PRIOR menu_id = p_menu_id) amt_child FROM t a