Oracle SQL 和 JOINS 的连续数字的间隔
Interval of consecutive numbers with Oracle SQL and JOINS
我正在尝试以如下形式在每行中显示冰岛连续海拔的间隔:
ELEVATION
0 27
29 33
35
37 40
42 46
48
51 63
现在,我只设法追踪差距,我有这样的想法:
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
谁能给我一些提示?
当前代码
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
输出
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
...
...
...
你已经完成一半了!您需要标记间隙的任一端,然后 select 仅那些行。
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
这将显示一行是起点还是终点。我们称之为 Q1。现在我们只是 select 我们需要的东西。
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
我正在尝试以如下形式在每行中显示冰岛连续海拔的间隔:
ELEVATION
0 27
29 33
35
37 40
42 46
48
51 63
现在,我只设法追踪差距,我有这样的想法:
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
谁能给我一些提示?
当前代码
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
输出
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
...
...
...
你已经完成一半了!您需要标记间隙的任一端,然后 select 仅那些行。
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
这将显示一行是起点还是终点。我们称之为 Q1。现在我们只是 select 我们需要的东西。
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