我正在尝试让sql返回memberid 2因为我希望得到连续值最大的成员,即使memberid 1是值1的四倍。
memberid position createdat
======== ======== =========
1 1 9/1/2001
1 1 8/1/2001
2 1 7/1/2001
2 1 6/1/2001
2 1 5/1/2001
1 1 4/1/2001
1 1 3/1/2001
万分感谢你的帮助。
答案 0 :(得分:1)
您需要使用参数作为计数器。在下面的@r中,每个行都会递增,只要该成员与前一行(由order by定义)相同,如果它不是同一个成员@r重置为1:
SELECT MemberID
FROM ( SELECT MemberID,
Position,
CreateDat,
@r:=IF(@m = MemberID, @r + 1, 1) AS Consec,
@m:= MemberID
FROM T,
(SELECT @r:= 0) r,
(SELECT @m:= 0) m
ORDER BY CreateDat DESC
) t
ORDER BY Consec DESC
LIMIT 1;
<强> Example on SQL Fiddle 强>
修改强>
稍微调整一下,您可以获得更多信息,例如连续期间的开始和结束时间:
SELECT MemberID, FirstCreateDat, CreateDat, Consec
FROM ( SELECT MemberID,
Position,
CreateDat,
@r:=IF(@m = MemberID, @r + 1, 1) AS Consec,
@d:=IF(@m = MemberID, @d, CreateDat) AS FirstCreateDat,
@m:= MemberID
FROM T,
(SELECT @r:= 0) r,
(SELECT @m:= 0) m,
(SELECT @d:= CAST(NULL AS DATETIME)) d
ORDER BY CreateDat DESC
) t
ORDER BY Consec DESC
LIMIT 1;
<强> Example on SQL Fiddle 强>