select * from ba_accounts
--insert into ba_accounts_level(ac_no,ac_no_level,ac_no_other,ac_no_other_level,no_top,cp_no)
with a as
(select level as ll, ac_no,cp_no --level 为所在级别123 本级为1 每上一级加1
from ba_accounts
where cp_no=v_cp_no
start with ac_no = v_data_no
connect by prior ac_top = ac_no )----查询v_data_no 及所有v_data_no的上级记录
select v_data_no as data_no,
max(ll) over() as no_level, ----非分组取最大 max(ll) over()
ac_no as name,
rank() over(order by ll desc) as id, --按 ll 反排序后 生成 id 排名列 重复排名占用名次位 (如两个第一下就个为第三,dense_rank()不占用)
case
when ac_no = v_data_no then
0
else
1
end,
cp_no
--,ll --3 2 1 (上面有order by ll desc)
from a;
----------Oracle 查询上下级:下级需要增加 distinct 去重
select distinct * from ba_accounts
--where cp_no=v_cp_no
start with ac_no = v_data_no
connect by prior ac_top = ac_no----查询v_data_no 及所有v_data_no的上级记录
select * from ba_accounts
--where cp_no=v_cp_no
start with ac_no = v_data_no
connect by prior ac_no = ac_top ----查询v_data_no 及所有v_data_no的下级记录
----------SQL SERVER 查询上下级:
select cp_no,cp_name,cp_top from sy_company
---------------------
select cp_no,cp_name,cp_top from sy_company
--查找条件节点及其所有上级节点带级别
with cte_parent(cp_no,cp_name,cp_top,level,gro)
as
(
select cp_no,cp_name,cp_top,0 as level,cp_no as gro from sy_company --where cp_no = '02'--列出子节点查询条件
union all
select a.cp_no,a.cp_name,a.cp_top,b.level+1,b.gro from sy_company a inner join cte_parent b--执行递归,这里就要理解下了
on a.cp_no=b.cp_top
)
select * from cte_parent order by gro,level;
--查找条件节点及其所有下级节点带级别
with cte_child(cp_no,cp_name,cp_top,level,gro)
as
(
select cp_no,cp_name,cp_top,0 as level,cp_no as gro from sy_company --where cp_no = '01'--列出父节点查询条件
union all
select a.cp_no,a.cp_name,a.cp_top,b.level+1,b.gro from sy_company a
inner join cte_child b on ( a.cp_top=b.cp_no)
)
select * from cte_child order by gro,level