【问题标题】:Output single row with latest record without null values Oracle输出具有最新记录且没有空值 Oracle 的单行
【发布时间】:2021-04-29 07:40:11
【问题描述】:

我有一张如下所示的表格。

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 为空,那么它应该从下一条记录中获取它。还假设对于单个对象将只有两行。

理想的输出应该是这样的。

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

【问题讨论】:

    标签: sql oracle oracle12c


    【解决方案1】:

    我唯一的想法就是自己加入你的桌子

    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
    

    UPD。如果 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  
    

    【讨论】:

    • 感谢您对此进行调查,但即使我正在以相同的方式接近,但考虑进一步优化它,或者如果可以使用任何功能来避免自加入,则可能会进一步优化。只是忘了提到我使用的是 12c 版本。
    • @AkashBurnwal 如果您有订购标准,您可以更轻松地进行操作。然后你可以使用“引导”函数
    • @AkashBurnwal 请检查我的更新答案。这个你可能会更好
    • 更新了一个也可以正常工作,而且更整洁。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多