如何查找数据库中的 连续字段 有多少条
如何查找数据库中的 连续字段 (比如某人连续登陆了多少天)
比如 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