0

所以我有一个读数表(下面是高度简化的版本)-有时阅读历史记录会中断(请参阅我标记为 N 的记录)-“从阅读”应始终与之前的“阅读”或'To Read' 应该总是匹配后面的 'From Read' 但我只想选择读取中第一个'break'的记录。

我将如何在 DB2 SQL 中编写查询以仅返回标有“Y”的行?

编辑:连续标志是我手动添加的以表示我想选择的记录,它在表上不存在。

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

提前致谢!Ĵ

4

2 回答 2

0

您将需要一个类似的递归选择:

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;
于 2014-12-05T13:26:37.697 回答
0

您可以使用lead(),来执行此操作lag()。我不确定您的情况的确切逻辑是什么,但我认为它类似于:

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;
于 2014-12-05T13:30:59.837 回答