Oracle SQL-如何按时间对比相关记录



给定以下列出的数据,如何仅选择记录,其中:

a) 存在相同client_id的至少1个先前票证,并且

b) 每个预处理票证的最大时间差可以不超过14天。换言之,如果票证具有a)中所述的继任者,并且该继任者已在>14天后创建,则不得考虑该继任者。

create table tickets (
ticket_id number,
client_id number,
start_time date);
insert into tickets values (1,1,to_date('201601011330','yyyymmddhh24mi'));
insert into tickets values (2,1,to_date('201601021320','yyyymmddhh24mi'));
insert into tickets values (3,1,to_date('201601101330','yyyymmddhh24mi'));
insert into tickets values (4,1,to_date('201603101330','yyyymmddhh24mi'));
insert into tickets values (5,2,to_date('201601011630','yyyymmddhh24mi'));
insert into tickets values (6,2,to_date('201601201330','yyyymmddhh24mi'));
insert into tickets values (7,3,to_date('201602011330','yyyymmddhh24mi'));
insert into tickets values (8,4,to_date('201602290000','yyyymmddhh24mi'));
insert into tickets values (9,4,to_date('201603011630','yyyymmddhh24mi'));
insert into tickets values (10,4,to_date('201604011120','yyyymmddhh24mi'));
insert into tickets values(11,4,to_date('201604101030','yyyymmddhh24mi'));
commit;

也可以不使用分析函数。

select * from tickets t1
  where exists (
    select 1 from tickets t2
      where t1.client_id = t2.client_id
        and t1.start_time>t2.start_time
        and t1.start_time<=t2.start_time+14
   );

您可以使用分析函数执行您想要的操作。我认为这就是逻辑:

select t.*
from (select t.*,
             row_number() over (partition by client_id order by start_time) as seqnum,
             lag(start_time) over (partition by client_id order by start_time) as prev_st
      from tickets t
     ) t
where (start_time - prev_st) < 14 and seqnum >= 2;

我意识到我不知道(b)中的"它"指的是什么——继承人是有问题的记录。正如所写的,seqnum >= 2是冗余的,因为每个客户端的第一条记录不符合第一个条件(prev_stNULL)。

如果这不是您所需要的,那么row_number()lag()lead()的某些组合似乎是正确的。

相关内容

  • 没有找到相关文章

最新更新