我有一个表格,其中包含数字(电话号码)和代码(免费或不可用)。
现在,我需要找到一系列连续的30个数字,例如079xxx100-079xxx130,并且所有这些数字都必须具有免费状态。
以下是我的表格外观示例:
CREATE TABLE numere
(
value int,
code varchar(10)
);
INSERT INTO numere (value,code)
Values
(123100, 'free'),
(123101, 'free'),
...
(123107, 'booked'),
(123108, 'free'),
(...
(123130, 'free'),
(123131, 'free'),
...
(123200, 'free'),
(123201, 'free'),
...
(123230, 'free'),
(123231, 'free'),
...
我需要一条SQL查询语句,在这个例子中,获取123200-123230范围内的内容(以及所有下一个可用的范围)。
现在,我找到了一个例子,基本上做到了我所需要的:
select value, code
from numere
where value >= (select a.value
from numere a
left join numere b on a.value < b.value
and b.value < a.value + 30
and b.code = 'free'
where a.code = 'free'
group by a.value
having count(b.value) + 1 = 30)
limit 30
但是这只返回了前30个可用数字,而不是在我的范围内(0-30)。 (而且需要13分钟才能执行,呵呵..)
如果有人有想法,请告诉我(我正在使用SQL Server)