连续区间(数据岛)查询
2017-05-04 22:16
591 查看
数据源如下
CREATE TABLE [dbo].[T1]( [col1] [int] NOT NULL, CONSTRAINT [PK_T1] PRIMARY KEY CLUSTERED ( [col1] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
T1中col1的序列号并不连续,我们需要找到现有值的连续区间,
方案1:使用子查询解决
select MIN(col1) as start_range,Max(col1) as end_range from
(select col1,(select MIN(B.col1) from T1 as B where B.col1>=A.col1 and not exists (select * from T1 as C where C.col1=B.col1+1)) as grp
from T1 as A) as D group by grp
方案2:使用窗口函数解决
select MIN(col1) as start_range,MAX(col1) as end_range from (select col1, col1-ROW_NUMBER() over(order by col1) as grp from T1) as A group by grp
相关文章推荐
- 查询不连续的数据
- SQL查询案例:利用笛卡尔积寻找连续日期中残缺的数据
- Hlookup区间数据查询
- POJ 题目2892 Tunnel Warfare(线段树单点更新查询,求单点所在最大连续区间长度)
- 面试时的一道SQL题(查询第30行至40行的数据(其中不可根据id来查,因为id并不一定连续))
- 数据表里面有DateTime字段, 日期和时间同时进行区间查询
- !SPOJ 1043 多次查询区间最大连续和-线段树
- HDU 3308 线段树 最长连续上升子序列 单点更新 区间查询
- SQL存储过程动态查询数据区间
- POJ 题目3667 Hotel(线段树,区间更新查询,求连续区间)
- sqlite数据库-查询某个区间的数据
- 【thinkphp3.x】thinkphp3.x中数据的查询-区间查询、统计查询等等
- 动态连续区间和查询,Binary Index Tree 算法
- SQL 查询连续区间
- HDU 3308 线段树 最长连续上升子序列 单点更新 区间查询
- SQL Server分页(查询某几条数据或某个区间内的几条数据)
- android SQLite 数据库 如何查询A和B区间的数据
- SQL查询案例:寻找连续日期中残缺的数据
- 查询第n条到第m条数据的sqlserver语句(其主键已经不再连续)
- HDU 1556 给连续个球涂色-线段树-(区间更新,单点查询)