我有以下作业表,在我们有5列中。
考虑job_id是主要键,而parent_job_id将为父作业为null,我给出了日期列值的数字值为了方便..请考虑下表数据
JOB_ID ABC XYZ DATE PARENT_JOB_ID
1 a b 1 null
2 a b 1 1
3 a b 2 1
7 a b 3 1
4 a b 3 null
5 a b 1 4
6 a b 2 4
在此中,我需要以一种应给我以下结果的方式查询
JOB_ID ABC XYZ PQR PARENT_JOB_ID
1 a b 1 null
7 a b 3 1
4 a b 3 null
6 a b 2 4
它们是父级的工作 最新的儿童工作(日期值为最大)
请帮助/建议。谢谢
如果您的数据库支持row_number()
分析功能,那么一种方法是获得
最新的儿童工作(日期值为最大)
使用row_number()
函数。
然后分别获取父作业(... where PARENT_JOB_ID is null
)
,然后UNION ALL
来自两个查询。
类似:
select * from (
select JOB_ID, ABC, XYZ, DATE, PARENT_JOB_ID from (
select *, row_number() over(partition by PARENT_JOB_ID order by DATE desc) rn
from your_table
where PARENT_JOB_ID is not null
) t
where rn = 1
union all
select JOB_ID, ABC, XYZ, DATE, PARENT_JOB_ID
from your_table
where PARENT_JOB_ID is null
) t
order by coalesce(PARENT_JOB_ID, JOB_ID) , JOB_ID