MySQL 没有 CTE 也没有窗口函数(例如 SUM OVER、ROW_NUMBER OVER 等)。但它有一个赎回因素。变量!
用这个:
select
min(date) as start_date,
max(date) as end_date,
count(date) as streak,
group_concat(gameid) as gameid_list
from
(
select *,
IF(
pointsfor > pointsagainst
and
@pointsfor > @pointsagainst,
@gn, @gn := @gn + 1)
as group_number,
@date as old_date, @gameid as old_gameid,
@pointsfor as old_pointsfor,
@pointsagainst as old_pointsagainst,
@date := date, @gameid := gameid,
@pointsfor := pointsfor, @pointsagainst := pointsagainst
from tbl
cross join
(
select
@date := CAST(null as date) as xa,
@gameid := null + 0 as xb, -- why CAST(NULL AS INT) doesn't work?
@pointsfor := null + 0 as xc, @pointsagainst := null + 0 as xd, @gn := 0
) x
order by date
) as y
group by group_number
order by streak desc;
输出:
START_DATE END_DATE STREAK GAMEID_LIST
March, 27 2011 08:00:00-0700 April, 10 2011 08:00:00-0700 3 17,23,30
June, 19 2011 08:00:00-0700 June, 19 2011 08:00:00-0700 3 74,77,80
May, 15 2011 08:00:00-0700 May, 22 2011 08:00:00-0700 2 48,56
March, 20 2011 08:00:00-0700 March, 20 2011 08:00:00-0700 1 15
April, 17 2011 08:00:00-0700 April, 17 2011 08:00:00-0700 1 35
May, 01 2011 08:00:00-0700 May, 01 2011 08:00:00-0700 1 38
May, 08 2011 08:00:00-0700 May, 08 2011 08:00:00-0700 1 43
May, 29 2011 08:00:00-0700 May, 29 2011 08:00:00-0700 1 59
June, 05 2011 08:00:00-0700 June, 05 2011 08:00:00-0700 1 65
June, 19 2011 08:00:00-0700 June, 19 2011 08:00:00-0700 1 71
现场测试:http ://www.sqlfiddle.com/#!2/bbe78/8
请注意我在 sqlfiddle 上的解决方案,它有两个查询。1. 模拟在上面。2.下面的最终查询