2016-03-04 102 views
0

我正在創建Rock Papper Scisors遊戲,我面臨的問題是我需要根據3,5或7的最佳設置獲勝者,並且要這樣做我需要計算連續querys的數我的投注表很簡單:獲得連續的行mysql

BO3

ID|GAME_ID|WINNER 
1 |145 |15 
2 |145 |14 
3 |145 |15 
4 |145 |15 

15只需要贏,我怎麼能計算出它在MySQL?

例如:

GAME_ID|WINNER|CONSECUTIVES 
    145|15 |2 

非常感謝。

+0

請編輯您的問題並提供樣品結果。 –

+0

沒有,請幫忙 –

回答

1

我想你會需要變量是:

select gameid, winner, max(rn) 
from (select s.*, 
      (@rn := if(@gw = concat_ws(':', gameid, winner), @rn + 1, 
         if(@gw := concat_ws(':', gameid, winner), 1, 1) 
         ) 
      ) as rn 
     from scores s cross join 
      (select @gw := '', @rn := 0) params 
     order by s.id 
    ) s 
group by gameid, winner; 

Here是SQL小提琴。

+0

沒有工作,打印像grup –

+0

你不考慮如果以前的結果不同,它不會計數,例如,winneris:15,15,14是1爲14 –

+0

@talles_jp。 。 。我修正了這一點。處理多個變量對於變量來說有點痛苦,所以可變鍵被連接在一起。 –

0

也許是這樣的:

select y.winner, 
    case when y2.cnt <= 3 then 'Best of 3' 
     when y2.cnt <= 5 then 'Best of 5' 
     when y2.cnt <= 7 then 'Best of 7' 
    end, count(*) 
from yourtable y join (
    select count(*) cnt, gameid 
    from yourtable 
    group by gameid) y2 on y.gameid = y2.gameid 
group by y.gameid, y.winner, y2.cnt 
having count(*) = 2 and y2.cnt <= 3 or 
count(*) = 3 and y2.cnt <= 5 or 
count(*) = 4 and y2.cnt <= 7 
+0

沒有急着我需要這樣的輸出: 遊戲|贏家|連續 145 | 15 | 2 –

+0

@talles_jp - 什麼是「連續」?在你更新你的問題之前,我正在猜測你的輸出... – sgeddes