我有一个带有数字列的表。有数据记录,让我们举例{1,7,10,11,12,19,20}。我想用SQL来获得下一个" free"来自特定x的数字:
>8 for x=7
>8 for x=8
>13 for x=10
>21 for x=20
有人有想法吗?
好的:我想插入带有' x'的东西。该列是唯一的,所以当已经有一个' 7'时,我不能在表中添加x = 7的内容。在那里。所以我想要一个让我回归的例行程序' 8'如果已经记录了' 7'。或者' 9'如果已经有了' 8'
IN Pseudo SQL:
x = 7 // for example
select COL from myTable where COL= (x or if x does not exist, the y : y > x, y - x smallest possible)
答案 0 :(得分:3)
Oracle 11g R2架构设置:
CREATE TABLE NUMBERS
("NUM" int)
;
INSERT ALL
INTO NUMBERS ("NUM")
VALUES (1)
INTO NUMBERS ("NUM")
VALUES (7)
INTO NUMBERS ("NUM")
VALUES (10)
INTO NUMBERS ("NUM")
VALUES (11)
INTO NUMBERS ("NUM")
VALUES (12)
INTO NUMBERS ("NUM")
VALUES (19)
INTO NUMBERS ("NUM")
VALUES (20)
SELECT * FROM dual
;
查询1 :
select min(n.VAL) as NextFree
from (
SELECT LEVEL as VAL
FROM DUAL
CONNECT BY LEVEL <= 100000
ORDER BY LEVEL
) n
left outer join NUMBERS d on n.VAL = d.NUM
where d.NUM is null
and n.VAL >= 10
<强> Results 强>:
| NEXTFREE |
|----------|
| 13 |
答案 1 :(得分:0)
类似于上面的答案,但不需要左联接:
select nvl(nextfree, 10) as nextfree from (
select max(d.NUM) + 1 as nextfree
from NUMBERS d
CONNECT BY PRIOR NUM + 1 = NUM
START WITH NUM = 10
)
| NEXTFREE |
|----------|
| 13 |