简体   繁体   中英

Interval of consecutive numbers with Oracle SQL and JOINS

I'm trying to display the intervals of consecutive elevations in Iceland, per row, in a form like this:

ELEVATION   
         0        27
         29       33
         35
         37       40
         42       46
         48
         51       63

For now, I only managed to track the gaps, I have something in mind like:

If the (count of the values in columnB until columnC='GAP') equals that value of columnB where columnC='GAP' THEN we have a consecutive interval between the value of columnA and column B

Can anyone give me some tips ?

current code

with x as (
    SELECT distinct elevation
    FROM CITIES
    WHERE iso = 'IS' AND iso IS NOT NULL
),y as (
    SELECT a.ELEVATION as "A",B.ELEVATION as "B",C.ELEVATION as "C"
FROM x a
   JOIN x b ON b.ELEVATION > a.ELEVATION
  LEFT JOIN x c ON c.ELEVATION > b.ELEVATION AND c.ELEVATION < b.ELEVATION + 2
)select y.A,y.B,y.C,case when y.C is null then 'GAP' else ' ' end  GAPZ from y
order by 1,2

output

 A  B   C   GAP
------------------
0   1   2    
0   2   3    
0   3   4    
...
...
...  
0   25  26   
0   26  27   
0   27      GAP
0   29  30   
0   30  31   
0   31  32   
0   32  33   
0   33      GAP
0   35      GAP
0   37  38   
0   38  39   
0   39  40   
0   40      GAP
0   42  43   
0   43  44   
0   44  45   
0   45  46   
0   46      GAP
0   48      GAP
0   51  52   
0   52  53   
...
...
...
0   61  62   
0   62  63   
0   63      GAP
0   65  66   
0   66  67   
0   67  68   
0   68  69   
0   69      GAP
0   71  72   
...
...
...

You're halfway there! You need to flag either end of the gap, then select only those rows.

Select x, 
            Case lead(x,x) over(order by x)
                 When x+1 then null
                 Else x
             End as endpoint,
             Case lag(x,x) over(order by x)
                  When x-1 then null
                  Else x
              End as startpoint
  From table

This will show whether a row is a start or endpoint. Let's call that Q1. Now we just select what we need from that.

Select Q1.startpoint,
            (Select min(endpoint)
               From Q1 as endp
             Where endp.endpoint >= Q1.x) as endpoint
 From Q1
 Where Q1.startpoint is not null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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