0

我试图让 sql 返回 memberid 2,因为我想获得最连续值为 1 的成员,即使 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

感谢一百万次的帮助。

4

1 回答 1

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;

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;

SQL Fiddle 示例

于 2013-09-26T22:10:24.830 回答