首先,我们需要来自两列的完整作业列表以及层次结构链接:
select
all_jobs.job_id as jobstream,
job_depends.follow_jobstream as parent_jobstream
from
(
select jobstream job_id from job_list
union
select follow_jobstream job_id from job_list
) all_jobs,
job_list job_depends
where
job_depends.jobstream (+) = all_jobs.job_id
然后确定每个工作的深度。
with full_job_list as (
select
all_jobs.job_id as jobstream,
job_depends.follow_jobstream as parent_jobstream
from
(
select jobstream job_id from job_list
union
select follow_jobstream job_id from job_list
) all_jobs,
job_list job_depends
where
job_depends.jobstream (+) = all_jobs.job_id
)
select
CONNECT_BY_ROOT jobstream as jobstream,
level as lvl,
CONNECT_BY_ROOT parent_jobstream as preceding_jobstream,
sys_connect_by_path(jobstream, '<-') as path_illustration
from
full_job_list
connect by
prior parent_jobstream = jobstream
最后根据深度安排工作。相同深度的作业可以按任何顺序工作。
with full_job_list as (
select
all_jobs.job_id as jobstream,
job_depends.follow_jobstream as parent_jobstream
from
(
select jobstream job_id from job_list
union
select follow_jobstream job_id from job_list
) all_jobs,
job_list job_depends
where
job_depends.jobstream (+) = all_jobs.job_id
)
select
jobstream,
depth,
preceding_jobstream
from (
select distinct
jobstream,
(
last_value(lvl ignore nulls)
over ( partition by jobstream
order by lvl
rows between unbounded preceding and unbounded following
)
) as depth,
(
last_value(preceding_jobstream ignore nulls)
over ( partition by jobstream
order by lvl
rows between unbounded preceding and unbounded following
)
) as preceding_jobstream
from (
select
CONNECT_BY_ROOT jobstream as jobstream,
level as lvl,
CONNECT_BY_ROOT parent_jobstream as preceding_jobstream
from
full_job_list
connect by
prior parent_jobstream = jobstream
)
)
order by depth, jobstream
SQL小提琴
更新更正以获得完整的工作列表并添加了先前的工作。
Update2更正了路径方向的错误。