DB2中如何使用SQL查找非连续数值
2013-01-31 10:03
441 查看
问题:
假设有一个表,一列int字段存放数字,值如: 1 2 3 4 5 8 9 10 20 21 22
其中1 2 3 4 5是连续的,8 9 10是连续的,20 21 22是连续的,请问如何用sql找出每个连续序列中的第一个数字,也就是找出1、8、20三个数字。
连续是指最少两个数字是相邻的,就可以看作为一个连续序列。
总的数据量不大,几万条到十几万条不等。这个操作是对已经收集到的数据做分析过滤用的,所以性能不用考虑太多。
初始化:
db2 create table test30 (col1 int)
db2 insert into test30 values 1, 2, 3, 4, 5, 8, 9, 10, 20, 21, 22
以下为每种方法和该方法使用的SQL语句的执行计划
方法1:
select col1 from test30 tt where tt.col1+1 in (select t.col1 from test30 t ) and tt.col1-1 not in (select t.col1 from test30 t )
方法2:
select col2+1 from ( select col2 from (select col1-1 col2 from test30) except select col1 col2 from test30 )
方法3:
with t ( n1,n2) as ( select col1, lag(col1,1) OVER(ORDER BY col1) AS col2 from test30 ) select n1 from t where (n2 is null ) or ( n1- n2 > 1)
方法4:
with tmp (num) as ( SELECT col1 FROM test30 ), tmp2 (num, next_num) as ( select num, coalesce(min(num) over(order by num rows between 1 following and 1 following), num+1) next_num from tmp) select num from ( select num, next_num-min(next_num) over(order by next_num rows between 1 preceding and 1 preceding) gap from tmp2 where next_num-num = 1) a where coalesce(gap,2) >1
相关文章推荐
- 如何查找硬解析问题,找到未使用绑定变量的SQL---脚本
- SQL 教程数据库包括:Oracle, Sybase, SQL Server, DB2, Access 等等,您将学到如何使用 SQL 访问和处理数据系统中的数据
- 数据库中如何使用SQL查询连续号码段
- 如何使用SQL语句查询连续编号中缺失的编号?
- 查找某张表中未使用到的连续数值
- 如何使用ArcIMS在MS SQLSERVER的ArcSDE中进行跨不同数据库的关联?-转载自ESRI中国在线支持中心
- 如何在store procedure中使用动态SQL
- 嵌入SQL中(DB2)异常处理WHENEVER语句的使用
- 使用SqlHelp.cs连接DB2
- 如何查找和使用 Office 对象模型文档
- 如何使用DataGrip导出整个数据库到一个.sql文件
- 在Sql语句中使用正则表达式来查找你所要的字符
- 如何使用sql查询数据库表结构的设计(sqlserver,oracle)
- (十六)maven实践-如何查找和使用插件
- 使用参数化SQL语句进行模糊查找
- Oracle PL/SQL中如何使用%TYPE和%ROWTYPE
- 【转】使用TCP协议连续传输大量数据时,是否会丢包,应如何避免?
- 如何在sql*plus中使用方向键(rlwrap@CentOS)
- LINQ to SQL 系列 如何使用LINQ to SQL插入、修改、删除数据 (转)
- MySQL GROUP_CONCAT函数使用示例:如何用一个SQL查询出一个班级各个学科第N名是谁?