我想在数字列(而不是整个列)中找到间隙,但是在特定范围中。
例如: 我的专栏:
1
2
5
6
8
10
18
19
20
我想指定一个特定的范围,在该范围内我的SQL查询会查找间隙。例如,我想要范围内的差距[15,20]。在这个例子中,间隙是:15,16,17。
我构建了一个检索间隙的查询,但不会检查间隙是否在我的范围的开头
SELECT cur_value + 1 AS start_gap, next_value - 1 AS end_gap
FROM (
SELECT col AS cur_value, LEAD (col) OVER (ORDER BY col) AS next_value
FROM table
--WHERE col BETWEEN 200 AND 300
)
WHERE next_value - cur_value > 1
ORDER BY start_gap;
我该怎么做?
N.B:在我的案例中,表现非常重要。我处理了很多行。
答案 0 :(得分:3)
我认为最简单的方法可能是:
SELECT cur_value + 1 AS start_gap, next_value - 1 AS end_gap
FROM (SELECT col AS cur_value, LEAD (col) OVER (ORDER BY col) AS next_value
FROM (SELECT col
FROM table
WHERE col BETWEEN 200 AND 300
UNION ALL
SELECT 200-1 FROM DUAL
UNION ALL
SELECT 300+1 FROM DUAL
) t
) t
WHERE next_value - cur_value > 1
ORDER BY start_gap;
注意:这适用于任意长距离。
答案 1 :(得分:2)
您可以简单地使用分层connect by
来生成给定范围内的数字列表,然后检查表中是否存在该值。
假设您的范围是15到20,请使用NOT IN
:
select * from (
select level - 1 + 15 col
from dual
connect by level <= 20 - 15
) where col not in (select col from your_table);
同样,NOT EXISTS
:
select * from (
select level - 1 + 15 col
from dual
connect by level <= 20 - 15
) t where not exists (select 1 from your_table where col = t.col);