2013-09-26 41 views
0

我試圖讓sql返回memberid 2,因爲我想獲得最多的成員連續的值爲1即使成員id 1爲四次值爲1.SQL獲得最大連續值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 

非常感謝任何幫助。

+1

你有一個排序列別的地方?您需要在查詢的上下文中建立「連續」的含義。 –

+0

我已經添加了一個created ...感謝 – Yannick

+0

看看這個問題:[MySQL Specific Group by](http://stackoverflow.com/questions/18796096/mysql-specific-group-by/) –

回答

1

您需要使用參數作爲計數器。在下面的@r被只要構件是相同的前一行(如由命令所定義的)遞增對於每一行,如果它不是@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

編輯

有輕微tweek你可以出去更多的信息,比如當連續週期的開始和結束:

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