oracle

时间:2017-12-20 16:19:49

标签: sql oracle oracle12c

我有一个包含数据[1,2,3,5,8,10,13,14]的专栏,我希望找到表格中的空白。

输出应该看起来像

MIN  MAX GAP
5    8   3
10   13  3
3    5   2 
8    10  2

感谢。

2 个答案:

答案 0 :(得分:2)

我想你只想要lead()

select t.col, t.next_col, (t.next_col - t.col) as gap
from (select t.*, lead(col) over (order by col) as next_col
      from t
     ) t
where t.next_col > t.col + 1;

答案 1 :(得分:2)

您将帖子标记为oracle12 - 这意味着您可以使用match_recognize子句获得简单有效的解决方案。如果您不熟悉WITH子句中的代码,请不要担心 - 我仅使用它来生成“测试数据”(它与您的问题的答案无关)。

with
  dataset ( val ) as (
    select column_value from table(sys.odcinumberlist(1,2,3,5,8,10,13,14))
  )
-- End of simulated inpus (for testing only, NOT PART OF THE SOLUTION).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select min, max, gap
from   dataset
match_recognize(
  order by    val
  measures    a.val         as min,
              b.val         as max,
              b.val - a.val as gap
  after match skip to next row
  pattern     ( a b )
  define      b as b.val > a.val + 1
);

       MIN        MAX        GAP
---------- ---------- ----------
         3          5          2
         5          8          3
         8         10          2
        10         13          3