输出带有最新记录的单行,没有空值 Oracle

Output single row with latest record without null values Oracle

我有一个 table 如下所示。

id job_id object message last_Exception second_last_Exception
312 1 abc deadlock 26-04-2021 null
312 0 abc connection reset null 25-04-2021
313 0 cde connection reset 25-04-2021 null
313 1 cde deadlock null 24-04-2021

基本上我必须打印每个对象的最新记录,如果 second_last_Exception_time 为 null 那么它应该从下一条记录中获取它。还假定对于单个对象只有两行。

理想情况下输出应该是这样的。

id job_id object message last_Exception second_last_Exception
312 1 abc deadlock 26-04-2021 25-04-2021
313 0 cde connection reset 25-04-2021 24-04-2021

我唯一的想法就是自己加入你们的 table

select t1.id, t1.job_id, t1.object, t1.message, t1.last_exception, t2.second_last_exception
  from some_table t1
  join some_table t2
    on t1.id = t2.id and t1.object = t2.object
 where t1.last_exception is not null
   and t2.second_last_exception is not null

更新。如果 second_last_exception 总是小于 last_exception(这对我来说似乎合乎逻辑),您可以在外部查询

中使用稍后不需要的引导函数和过滤行
select * 
  from (select id, job_id, message, last_exception, 
        lead(second_last_exception) over(partition by id, object order by nvl(last_exception, second_last_exception) desc) sec_last_exc
          from some_table)
 where last_exception is not null