看这篇文章之前可以先看下面的文章
oracle递归查询(start with connect by prior)以及 树形统计connect_by_root(子节点汇总到父节点).
数据来源和这篇文章里的一样,所有下面用到就直接给sql了,自己想复制数据的话,可以去上篇文章里拿
3.3.2章节
create or replace function f_company_id(v_dept_id varchar2) return varchar2 is
company_id varchar2(100);
count_num number;
begin
select count(0) into count_num from sys_company_dept t where t.dept_id = v_dept_id and type = '1';
if count_num = 1 then
return v_dept_id;
else
select f_company_id(t.parent_id) into company_id from sys_company_dept t where t.dept_id = v_dept_id and rownum < 2;
return company_id;
end if;
end f_company_id;
with temp1 as(
select t.*,f_company_id(t.dept_id) company_id
from sys_company_dept t)
select t1.*,t2.dept_name as company_name from temp1 t1
left join sys_company_dept t2 on t1.company_id=t2.dept_id
where t2.type='1';