简体   繁体   English

在DB2 SQL中仅选择连续记录

[英]Select only Contiguous Records in DB2 SQL

So i have a table of readings (heavily simplified version below) - sometimes there is a break in the reading history (see the record i have flagged as N) - The 'From Read' should always match a previous 'To Read' or the 'To Read' should always match a later 'From Read' BUT I want to only select records as far back as the first 'break' in the reads. 因此,我有一个阅读表(以下为简化版本)-有时阅读历史记录有所中断(请参阅我标记为N的记录)-“从阅读”应始终与以前的“阅读”相匹配“要读取”应始终与后来的“从读取”匹配,但我只希望选择回溯到读取中第一个“中断”的记录。

How would i write a query in DB2 SQL to only return the rows flagged with a 'Y'? 我将如何在DB2 SQL中编写查询以仅返回标有'Y'的行?

EDIT: The contiguous flag is something i have added manually to represent the records i would like to select, it does not exist on the table. 编辑:连续标志是我手动添加的东西,代表我想选择的记录,它在表上不存在。

ID  From        To          Contiguous
ABC 01/01/2014  30/06/2014  Y
ABC 01/06/2013  01/01/2014  Y
ABC 01/05/2013  01/06/2013  Y
ABC 01/01/2013  01/02/2013  N
ABC 01/10/2012  01/01/2013  N

Thanks in advance! 提前致谢! J Ĵ

you will need a recursive select something like that: 您将需要一个递归选择类似的东西:

WITH RECURSIVE
 contiguous_intervals(start, end) AS (
    select start, end
    from intervals
    where end = (select max(end) from intervals)
 UNION ALL
    select i.start, i.end
    from contiguous_intervals m, intervals i
    where i.end = m.start
)
select * from contiguous_intervals;

You can do this with lead() , lag() . 您可以使用lead()lag()做到这一点。 I'm not sure what the exact logic is for your case, but I think it is something like: 我不确定您的情况的确切逻辑是什么,但是我认为这类似于:

select r.*,
       (case when (prev_to = from or prev_to is null) and
                  (next_from = to or next_from is null)
             then 'Y'
             else 'N'
        end) as Contiguous
from (select r.*, lead(from) over (partition by id order by from) as next_from,
             lag(to) over (partition by id order by to) as prev_to
      from readings r
     ) r;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM