静·谧——Last Winner
===========================================================
===========================================================

此文应与http://blog.itpub.net/post/7102/48132对比阅读
相关文章:http://lastwinner.itpub.net/post/7102/248528

问题的提出:

table T,列:serial_no
我想能够查询一下serial_no这个字段的不连续的值。
例如:
serial_no
1
2
3
4
6
8
9
10
我想一个sql语句查出来缺失的号码,
显示结果为:
5
7
http://www.itpub.net/435578.html


RollingPig的方法:

SELECT /*+ordered */
T2.n + 1, MIN (t3.n) - 1
FROM TTT T1, TTT T2, TTT t3
WHERE T1.n(+) = (T2.n + 1) AND T1.n IS NULL
AND t3.n > T2.n
GROUP BY T2.n

他的解决思路是这样的:

解决思路:

1。用not exists /not in ,条件 : t1.serial_no = t2.serial_no + 1

2。参考http://www.itpub.net/406784.html , 将not exists /not in 改为outer join + is null 格式

3。加上 min 条件,确定上下限
有空再列出详细步骤
http://blog.itpub.net/post/81/42842

很巧妙的方法,等待他的详细步骤:)

我的方法:
create table TTT(n number(10));
insert into ttt select rownum from all_objects where rownum<10;
delete from ttt where n=2;
delete from ttt where n>=2 and n<=6;
insert into ttt select rownum+12 from user_tables where rownum<10;
insert into ttt select rownum+22 from user_objects where rownum<=6;
insert into ttt select rownum+29 from user_objects where rownum<=6;
insert into ttt select rownum+39 from user_objects where rownum<=6;
commit;
SQL> select * from ttt;

N
----------
1
30
31
32
33
34
7
8
9
13
14
15
16
17
18
19
20
21
23
24
25
26
27
28
35
40
41
42
43
44
45

SQL> select * from (select n,n-lag(n,1)over(order by n)-1 dis ,
2 lag(n,1)over(order by n)+1 S, n-1 E from ttt) where dis<>0;

N DIS S E
---------- ---------- ---------- ----------
7 5 2 6
13 3 10 12
23 1 22 22
30 1 29 29
40 4 36 39

N为与前一个数字不连续的数字,dis为不连续的数字的数目,S为起点,E为终点

利用all_objects构造序列,假设dis的最大值不超过100
SQL> select orn+t.S-1 from (select rownum orn from all_objects where rownum<100)
o,
2 (select rownum rn, n, dis, S, E from (select n,n-lag(n,1)over(order by n)-1
dis ,
3 lag(n,1)over(order by n)+1 S, n-1 E from ttt) where dis<>0) t
4 where orn<=t.E-t.S+1;

ORN+T.S-1
----------
2
3
4
5
6
10
11
12
22
29
36
37
38
39

已选择14行。

原文地址:http://www.itpub.net/showthread.php?s=&postid=3203034

lastwinner 发表于:2005.11.04 17:42 ::分类: ( Oracle , ) ::阅读:(4182次) :: 评论 (1)
re: 如何取不连续的值 [回复]

反过来怎么求解啊
就是知道连续的或是不连续的值,拆成连续的记录

zzw0598 评论于: 2006.05.22 11:16

发表评论
标题

在此添加评论
表情符号: smile laughing tongue angry crying sad wassat wink

称呼

邮箱地址(可选)

个人主页(可选)

 authimage


自我介绍
切换风格
新闻聚合
博客日历
文章归档...
最新发表...
最新评论...
最多阅读文章...
最多评论文章...
博客统计...
Blog信息
网站链接...