如何根据多个过滤条件动态获取记录

时间:2019-06-22 11:16:04

标签: sql oracle oracle11g

我有下表:

enter image description here

您能帮我如何动态获取以下情况的结果吗?

如果我提供Emp = 1且HeaderID = 123且Status = Failed,则它应返回如下结果:

EmpID HeaderID Status XML_Payload1 123 Failed <xml>1 321 Pending <xml>1 555 Pending <xml>2.

如果我提供Emp = 1且HeaderID = 111且status = Failed,它将返回以下结果:

enter image description here

请先谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您需要再显示一列,例如时间或额外的ID或金额,以便在显示数据时进行排序。为了提供此条件,我在您的数据中添加了一个时间列(time,如下面的演示所示:

with t(empid,headerid,status,time) as
(
 select 1,123,'Failed' , '2019-06-22 17:00:00' from dual union all
 select 1,321,'Pending', '2019-06-22 17:10:00' from dual union all
 select 1,555,'Pending', '2019-06-22 17:20:00' from dual union all
 select 1,111,'Failed' , '2019-06-22 17:30:00' from dual union all
 select 1,222,'Pending', '2019-06-22 17:40:00' from dual union all
 select 2,333,'Failed' , '2019-06-22 17:50:00' from dual union all
 select 2,444,'Pending', '2019-06-22 18:00:00' from dual union all
 select 3,555,'Failed' , '2019-06-22 18:10:00' from dual 
), t2 as  
(
select sum(case when status = 'Failed' then 1 else 0 end) 
       over (partition by empid order by time) as rn,
       t.*
  from t
) 
select *
  from t2
 where (rn, empid) in 
          ( select rn, empid 
              from t2 
             where empid = &i_empid -- 1 
               and headerid = &i_headerid -- 123
               and status = 'Failed' )
 order by time;

您可以用1123111123333和{{ 1}},如您所愿。

Demo

编辑因您的评论):

如果要返回状态为555的第一行,紧接着返回状态为Pending的第一行,则可以尝试使用:

Failed

再次,您可以替换上面查询中使用的相同值。