日期:2014-05-18  浏览次数:20620 次

求解一个月中连续登陆天数的最大值
如何求取一个月中连续登陆天数最大值问题,不使用游标怎么解决。有一个思路是:某天登陆记为1,没有登陆记为0.这样一个月中就会出现111010。。。。。这样的形式,不过后面我就不知道怎么写SQL了。

测试数据如下:
create table LoginTable (name varchar(10),logindate datetime)
insert into LoginTable values('A','2011-03-07'),
('A','2011-03-1'),
('A','2011-03-2'),
('A','2011-03-3'),
('A','2011-03-6'),
('A','2011-03-8'),
('A','2011-03-10'),
('A','2011-03-11'),
('A','2011-03-12'),
('A','2011-03-15'),
('A','2011-03-16'),
('A','2011-03-20'),
('A','2011-03-25'),
('A','2011-03-29');



------解决方案--------------------
SQL code

create table LoginTable (name varchar(10),logindate date)
insert into LoginTable 
values
('A','2011-03-07'),
('A','2011-03-1'),
('A','2011-03-2'),
('A','2011-03-3'),
('A','2011-03-6'),
('A','2011-03-8'),
('A','2011-03-10'),
('A','2011-03-11'),
('A','2011-03-12'),
('A','2011-03-15'),
('A','2011-03-16'),
('A','2011-03-20'),
('A','2011-03-25'),
('A','2011-03-29');

with d as
(
select logindate,(select min(b.logindate) from LoginTable b where b.logindate>=a.logindate
and not exists (select * from LoginTable c where c.logindate=dateadd(dd,1,b.logindate))) as grp
from LoginTable a
),
m as(
select min(logindate) as start_range,max(logindate) as end_range
from d group by grp)
select max(DATEDIFF(DD,start_range,end_range)+1) as maxday from m
where DATEDIFF(DD,start_range,end_range)<>0

/*
maxday
3
*/

------解决方案--------------------
探讨
从数值表上看很明显最大天数是3,怎么会是2呢?好像我换表中数据之后,该程序结果始终为2。