尝试如下
select
mainqry.userid,
max(mainqry.daysdiff) as max_date_diff
From
(
select
qry.userid,
-- qry.id1,
-- qry.currid,
( Case when qry.id1 = qry.currid then qry.dt1 else null end ) prevconndt,
qry.currdt,
datediff((Case when qry.id1 = qry.currid then qry.dt1 else null end),qry.currdt) daysdiff
from
(
select
userid,
@previd id1,
@previd := userid as currid,
@prevdt dt1,
@prevdt := connectiondate as currdt
from table1,(select @prevdt:=NULL,@previd := NULL) a
order by userid, connectiondate desc
) qry
) MainQry
group by MainQry.userid;
它会在下面输出你给定的数据
Userid max_date_diff
1 4
2 5
3 5
4 Null
您也可以使用下面的方法进行验证...
select
qry.userid,
-- qry.id1,
-- qry.currid,
( Case when qry.id1 = qry.currid then qry.dt1 else null end ) prevconndt,
qry.currdt,
datediff((Case when qry.id1 = qry.currid then qry.dt1 else null end),qry.currdt) daysdiff
from
(
select
userid,
@previd id1,
@previd := userid as currid,
@prevdt dt1,
@prevdt := connectiondate as currdt
from table1,(select @prevdt:=NULL,@previd := NULL) a
order by userid, connectiondate desc
) qry