I need some help pulling records that happen in a sequence in the MySQL environment.
My dataset consists of cross-country games and the winning and losing country. I need to identify countries which have won atleast 3 games in a row. Below is a reproducible example. I created a matches dataset.
CREATE TABLE matches (date DATE, winner CHAR(10), loser CHAR(10));
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-03-2013', '%m-%d-%Y') ,'USA','CHINA');
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-05-2013', '%m-%d-%Y') ,'USA','RUSSIA');
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-06-2013', '%m-%d-%Y') ,'FRANCE','GERMANY');
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-09-2013', '%m-%d-%Y') ,'USA','RUSSIA');
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-11-2013', '%m-%d-%Y') ,'USA','INDIA');
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-15-2013', '%m-%d-%Y') ,'USA','AUSTRALIA');
INSERT INTO matches (date,winner,loser) VALUES (STR_TO_DATE('3-15-2013', '%m-%d-%Y') ,'USA','NEW ZEALAND');
I created another dataset which has a row number for each country ordered by date.
CREATE TABLE matches2
(
date DATE,
winner CHAR(10),
loser CHAR(10),
row INT
);
INSERT INTO matches2
(
row,
winner,
date,
loser
)
SELECT row,
winner,
date ,
loser
FROM
(
SELECT winner,
(@winner:=@winner+1) AS row,
date ,
loser
FROM matches ,
(SELECT @winner := 0) r
) x
ORDER BY date;
The table matches2 looks like below
date winning losing row
2013-03-03 USA CHINA 1
2013-03-05 USA RUSSIA 2
2013-03-06 FRANCE GERMANY 3
2013-03-09 USA RUSSIA 4
2013-03-11 USA INDIA 5
2013-03-15 USA AUSTRALIA 6
2013-03-15 USA NEW ZEALAN 7
As the data shows, USA has won >3 games in a row. how I write a code to capture this sequence ?