日期:2014-05-16 浏览次数:20967 次
--抛砖引玉 [SYS@myoracle] SQL>WITH T1 AS 2 (SELECT 1 ID, '中国' MINGZI, NULL PID 3 FROM DUAL 4 UNION ALL 5 SELECT 2 ID, '福建' MINGZI, 1 PID 6 FROM DUAL 7 UNION ALL 8 SELECT 3 ID, '浙江' MINGZI, 1 PID 9 FROM DUAL 10 UNION ALL 11 SELECT 4 ID, '三明' MINGZI, 2 PID 12 FROM DUAL 13 UNION ALL 14 SELECT 5 ID, '福州' MINGZI, 2 PID 15 FROM DUAL 16 UNION ALL 17 SELECT 6 ID, '杭州' MINGZI, 3 PID 18 FROM DUAL 19 UNION ALL 20 SELECT 7 ID, '绍兴' MINGZI, 3 PID FROM DUAL), 21 T2 AS 22 (SELECT ID, 23 MINGZI, 24 PID, 25 CONNECT_BY_ROOT ID IID, 26 RTRIM(LTRIM(SYS_CONNECT_BY_PATH(PID, ','), ','), ',') P 27 FROM T1 28 START WITH ID IN (4, 5, 6, 7) 29 CONNECT BY ID = PRIOR PID), 30 T3 AS 31 (SELECT IID, MAX(P) P FROM T2 GROUP BY IID) 32 SELECT T1.ID, T1.MINGZI, T3.P FROM T1, T3 WHERE T1.ID = T3.IID ORDER BY ID 33 ; ID MING P ---------- ---- ----- 4 三明 2,1 5 福州 2,1 6 杭州 3,1 7 绍兴 3,1 [SYS@myoracle] SQL>
------解决方案--------------------
SELECT t.dept_id,--id t.dept_name,--name SYS_CONNECT_BY_PATH(dept_name, '->') path1, substr(sys_connect_by_path(dept_name, '>'), 2) path2,--path CONNECT_BY_ROOT(t.dept_id) top_id --top FROM t_com_dept_info t START WITH t.parent_id IS NULL CONNECT BY PRIOR t.dept_id = t.parent_id