MySQL の最新バージョンには CTE があり、ウィンドウ対応です。
これが解決策です。
最初のステップでは、グループの勝者と敗者に独自の streak_group 番号を割り当てます。
with t as
(
select
*,
pointsfor - pointsagainst > 0 is_winner,
case when pointsfor - pointsagainst > 0
and lag(pointsfor) over(order by date, pointsfor - pointsagainst desc)
- lag(pointsagainst) over(order by date, pointsfor - pointsagainst desc) > 0
then
0
else
1
end as is_new_group
from tbl
)
select *, sum(is_new_group) over(order by date, pointsfor - pointsagainst desc) as streak_group
from t
出力:
date |gameid |pointsfor |pointsagainst |is_winner |is_new_group |streak_group |
--------------------|-------|----------|--------------|----------|-------------|-------------|
2011-03-20 15:00:00 |15 |1 |10 |0 |1 |1 |
2011-03-27 15:00:00 |17 |7 |3 |1 |1 |2 |
2011-04-03 15:00:00 |23 |6 |5 |1 |0 |2 |
2011-04-10 15:00:00 |30 |5 |4 |1 |0 |2 |
2011-04-17 15:00:00 |35 |4 |8 |0 |1 |3 |
2011-05-01 15:00:00 |38 |8 |1 |1 |1 |4 |
2011-05-08 15:00:00 |43 |3 |7 |0 |1 |5 |
2011-05-15 15:00:00 |48 |6 |2 |1 |1 |6 |
2011-05-22 15:00:00 |56 |10 |2 |1 |0 |6 |
2011-05-29 15:00:00 |59 |4 |5 |0 |1 |7 |
2011-06-05 15:00:00 |65 |2 |3 |0 |1 |8 |
2011-06-19 15:00:00 |74 |12 |2 |1 |1 |9 |
2011-06-19 15:00:00 |77 |5 |2 |1 |0 |9 |
2011-06-19 15:00:00 |80 |5 |4 |1 |0 |9 |
2011-06-19 15:00:00 |71 |5 |6 |0 |1 |10 |
最終クエリ。連勝数を数えます。
with t as
(
select
*,
pointsfor - pointsagainst > 0 is_winner,
case when pointsfor - pointsagainst > 0
and lag(pointsfor) over(order by date, pointsfor - pointsagainst desc)
- lag(pointsagainst) over(order by date, pointsfor - pointsagainst desc) > 0
then
0
else
1
end as is_new_group
from tbl
)
, streak_grouping as
(
select
*, sum(is_new_group) over(order by date, pointsfor - pointsagainst desc) as streak_group
from t
)
select
min(date) as start_date,
max(date) as end_date,
count(*) as streak,
group_concat(gameid order by gameid) as gameid_list
from streak_grouping
group by streak_group
order by streak desc, start_date
出力:
start_date |end_date |streak |gameid_list |
--------------------|--------------------|-------|------------|
2011-03-27 15:00:00 |2011-04-10 15:00:00 |3 |17,23,30 |
2011-06-19 15:00:00 |2011-06-19 15:00:00 |3 |74,77,80 |
2011-05-15 15:00:00 |2011-05-22 15:00:00 |2 |48,56 |
2011-03-20 15:00:00 |2011-03-20 15:00:00 |1 |15 |
2011-04-17 15:00:00 |2011-04-17 15:00:00 |1 |35 |
2011-05-01 15:00:00 |2011-05-01 15:00:00 |1 |38 |
2011-05-08 15:00:00 |2011-05-08 15:00:00 |1 |43 |
2011-05-29 15:00:00 |2011-05-29 15:00:00 |1 |59 |
2011-06-05 15:00:00 |2011-06-05 15:00:00 |1 |65 |
2011-06-19 15:00:00 |2011-06-19 15:00:00 |1 |71 |