仅为数字+1选择范围(最小,最大)

时间:2018-12-26 19:31:54

标签: oracle gaps-and-islands

仅为数字+1的范围选择范围(最小值,最大值)

有一张桌子:

col_number
1
2
3
4
9
10
12

必须如此获取数据:

min   max
1     4
9     10
12    12

4 个答案:

答案 0 :(得分:2)

这称为间隙和孤岛问题。您可以通过从值中减去行号来获得组键来解决此问题:

select min(col), max(col)
from
(
  select
    col,
    col - row_number() over (order by col) as grp
  from mytable
) 
group by grp
order by min(col);

答案 1 :(得分:2)

在Oracle 12.1或更高版本中,您可以像这样使用match_recognize

with
  my_table(col_number) as (
    select  1 from dual union all
    select  2 from dual union all
    select  3 from dual union all
    select  4 from dual union all
    select  9 from dual union all
    select 10 from dual union all
    select 12 from dual
  )
-- end of sample data (for testing only, not part of the solution)
select min_number, max_number
from   my_table
match_recognize(
  order by col_number
  measures first(col_number) as min_number, last(col_number) as max_number
  pattern  (a b*)
  define b as col_number = prev(col_number) + 1
);

MIN_NUMBER MAX_NUMBER
---------- ----------
         1          4
         9         10
        12         12

答案 2 :(得分:1)

在Oracle中,您实际上可以在没有窗口功能的情况下执行此操作:

-DtestApp=app2

答案 3 :(得分:0)

没有窗口功能:

WITH 
nmin AS (
  SELECT col_number FROM numbers t WHERE NOT EXISTS 
    (SELECT col_number FROM numbers WHERE numbers.col_number = t.col_number - 1)),
nmax AS (
  SELECT col_number FROM numbers t WHERE NOT EXISTS 
    (SELECT col_number FROM numbers WHERE numbers.col_number = t.col_number + 1))
SELECT 
  nmin.col_number minnumber, 
  (SELECT MIN(nmax.col_number) FROM nmax WHERE nmax.col_number >= nmin.col_number) maxnumber
FROM nmin
ORDER BY nmin.col_number;