日期:2014-05-17  浏览次数:20464 次

如何查找数据库中的 连续字段 有多少条
如何查找数据库中的 连续字段 (比如某人连续登陆了多少天)

比如   1 ,2 ,4 ,5, 6  

分两种情况

1.比如查询某人连续登陆了多少天  (这个还好一点,只要查和当前时间最近的连续数)

2.这种情况比较复杂  , 例如:   1 ,2 ,4 ,5, 6    1和2连续    456也连续   这种情况怎么办?

听听大家的意见!!

------解决方案--------------------
--查找连续编号区间

create table test(field varchar(03))
insert into test values('001')
insert into test values('002')
insert into test values('003')
insert into test values('005')
insert into test values('006')
insert into test values('008')
insert into test values('010')
insert into test values('011')
insert into test values('015')
insert into test values('016')
insert into test values('017')
 
go
;with cte_test
as
(
select field, field as new_field
from test as T
where not exists(select 1 from test where convert(int,field) = convert(int,T.field)-1)
union all
select A.field,B.field
from cte_test as A, test as B
where convert(int,A.new_field)+1= convert(int,B.field)
)
select field as [start],max(new_field) as [end]
 from cte_test
group by field
order by [start]
 
/*
001 003
005 006
008 008
010 011
015 017
*/
GO
drop table test

------解决方案--------------------
错位自乘:
from tb a
left join tb b on a.x=b.x-1
------解决方案--------------------
可以自己创建个数字辅助表,如果数量少在2048一下的话可以借助系统辅助表
select * From master..spt_values where type='p'
与其关联查询就能查到连续的数据了,外连接的话就会看出哪里断掉