编写mySQL来获取序列

时间:2014-01-26 20:16:08

标签: mysql

我需要获得特定运动队的胜负序列。例如:

表:结果

teamid    win  eventdate
======    ===  =========
1         0    26/01/2014
1         0    25/01/2014
2         1    26/01/2014
1         0    24/01/2014 
1         1    21/01/2014

它应该返回teamid 1有3个丢失的序列。但是我怎么能在sql中做到这一点?

1 个答案:

答案 0 :(得分:1)

MySQL不支持分析函数,但计算顺序获胜/亏损的一种方法是user variables

SELECT   @seq    := IF(@teamid<=>teamid AND @win<=>win,@seq,0)+1 seq,
         @teamid := teamid teamid,
         @win    := win win
FROM     RESULTS, (SELECT @teamid:=NULL, @win:=NULL) init
ORDER BY teamid, STR_TO_DATE(eventdate, '%d/%m/%Y')

此查询可用作执行进一步分析的基础。例如,要获得团队最长的条纹(包括输赢):

SELECT teamid, win, MAX(seq) FROM (
  SELECT   @seq    := IF(@teamid<=>teamid AND @win<=>win,@seq,0)+1 seq,
           @teamid := teamid teamid,
           @win    := win win
  FROM     RESULTS, (SELECT @teamid:=NULL, @win:=NULL) init
  ORDER BY teamid, STR_TO_DATE(eventdate, '%d/%m/%Y')
) t GROUP BY teamid, win