Finding A Sporting Team Streak in MySQLMySQL optimization - year column grouping - using temporary table,...

Are there any rules for handling distractions whilst performing skill checks?

Buying a "Used" Router

Is there a name for this series?

Is it possible to narrate a novel in a faux-historical style without alienating the reader?

How to make transparent background from pdf to png

Why does this quiz question say that protons and electrons do not combine to form neutrons?

Why can all solutions to the simple harmonic motion equation be written in terms of sines and cosines?

What is the smallest molar volume?

When distributing a Linux kernel driver as source code, what's the difference between Proprietary and GPL license?

Was the Soviet N1 really capable of sending 9.6 GB/s of telemetry?

Can I do anything else with aspersions other than cast them?

How bad is a Computer Science course that doesn't teach Design Patterns?

Distribution of sum of independent exponentials with random number of summands

How can I prep for the Curse of Strahd adventure effectively?

How many copper coins fit inside a cubic foot?

Trying to make a 3dplot

Python to write multiple dataframes and highlight rows inside an excel file

I am a loser when it comes to jobs, what possibilities do I have?

Why is it that Bernie Sanders always called a "socialist"?

How does holding onto an active but un-used credit card affect your ability to get a loan?

Why do single electrical receptacles exist?

How can a Sorcerer/Warlock use 4 Eldritch blasts in one round?

What does @ mean in a hostname in DNS configuration?

Coworker asking me to not bring cakes due to self control issue. What should I do?



Finding A Sporting Team Streak in MySQL


MySQL optimization - year column grouping - using temporary table, filesort“Lost connection to MySQL server during query” errorMySQL : Avoid Temporary/Filesort Caused by GROUP BY Clause in ViewsMysql join not workingcase statement when grouping?mysql: counting number of tickets which are open per day basisOptimizing a simple query on a large tableHow to improve query count execution with mySql replicate?Design a betting system for Fifa World Cup Russia 2018select MAX() from MySQL view (2x INNER JOIN) is slow













0















I have a table Schedule for a local high school football conference. This is in MySQL. My goal is to include the "streak" for each team. If a team wins 2 games in a row the streak is W2, or if a team loses 4 games in a row, the streak would be L4.



Here's my table schema:



CREATE TABLE `Schedule` (
`ScheduleId` int(10) NOT NULL auto_increment COMMENT 'Schedule Id',
`SportId` int(11) NOT NULL COMMENT 'Sport Id',
`HomeTeamId` int(10) NOT NULL COMMENT 'Home Team Id',
`AwayTeamId` int(11) NOT NULL COMMENT 'Away Team Id',
`StartTime` datetime NOT NULL COMMENT 'Start Time of Event',
`HomeTeamFinal` double default NULL COMMENT 'Final Score of Home Team',
`AwayTeamFinal` double default NULL COMMENT 'Final Score of Away Team',
`IsRegularSeason` bit(1) NOT NULL default b'1',
PRIMARY KEY (`ScheduleId`)
)


I currently have a "Standings" query that shows the Won, Loss, Total, PF, PA, Percentage and Games Behind or each team. However, with this, I wanted to include the streak of each team.



My Standings SQL is as follows:



SELECT  T.SchoolName, R.Won AS W, R.Lost AS L, R.Total AS T, R.PF, R.PA, R.GB, R.Percentage AS P
FROM Teams AS T
INNER JOIN (
SELECT TeamId,
SUM(Win) As Won,
SUM(Loss) as Lost,
SUM(Win+Loss) as Total,
PtsFor AS PF,
PtsAgainst AS PA,
CASE WHEN (SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss))=0 THEN '--'
ELSE ROUND(ABS((SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss)))/2,1) END GB,
ROUND((SUM(Win)/SUM(Win+Loss)*100),2) AS Percentage
FROM WinsLosses AS R
GROUP BY TeamId
ORDER By Won DESC
) R ON T.Id = R.TeamId
ORDER BY R.PF DESC, T.SchoolName


And my WinsLosses view is:



select 
`Schedule`.`HomeTeamId` AS `TeamId`,
(case when (`Schedule`.`HomeTeamFinal` > `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`HomeTeamFinal` < `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`HomeTeamFinal` AS `PtsFor`,
`Schedule`.`AwayTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`HomeTeamFinal` != '0') and (`Schedule`.`AwayTeamFinal` != '0'))

union all

select
`Schedule`.`AwayTeamId` AS `TeamId`,
(case when (`Schedule`.`AwayTeamFinal` > `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`AwayTeamFinal` < `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`AwayTeamFinal` AS `PtsFor`,
`Schedule`.`HomeTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`AwayTeamFinal` != '0') and (`Schedule`.`HomeTeamFinal` != '0'))


I've been trying to figure this out for a couple days and am stuck. How would you best go about doing a streak with this database schema.










share|improve this question














bumped to the homepage by Community 11 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 2





    If the sequence is W,W,W,L,W,W -- Is that a W3 (the longest), or W2 (leading up to 'now')?

    – Rick James
    Aug 25 '17 at 15:50











  • Would be great if you included a data sample and the expected result for it.

    – Andriy M
    Aug 26 '17 at 15:34
















0















I have a table Schedule for a local high school football conference. This is in MySQL. My goal is to include the "streak" for each team. If a team wins 2 games in a row the streak is W2, or if a team loses 4 games in a row, the streak would be L4.



Here's my table schema:



CREATE TABLE `Schedule` (
`ScheduleId` int(10) NOT NULL auto_increment COMMENT 'Schedule Id',
`SportId` int(11) NOT NULL COMMENT 'Sport Id',
`HomeTeamId` int(10) NOT NULL COMMENT 'Home Team Id',
`AwayTeamId` int(11) NOT NULL COMMENT 'Away Team Id',
`StartTime` datetime NOT NULL COMMENT 'Start Time of Event',
`HomeTeamFinal` double default NULL COMMENT 'Final Score of Home Team',
`AwayTeamFinal` double default NULL COMMENT 'Final Score of Away Team',
`IsRegularSeason` bit(1) NOT NULL default b'1',
PRIMARY KEY (`ScheduleId`)
)


I currently have a "Standings" query that shows the Won, Loss, Total, PF, PA, Percentage and Games Behind or each team. However, with this, I wanted to include the streak of each team.



My Standings SQL is as follows:



SELECT  T.SchoolName, R.Won AS W, R.Lost AS L, R.Total AS T, R.PF, R.PA, R.GB, R.Percentage AS P
FROM Teams AS T
INNER JOIN (
SELECT TeamId,
SUM(Win) As Won,
SUM(Loss) as Lost,
SUM(Win+Loss) as Total,
PtsFor AS PF,
PtsAgainst AS PA,
CASE WHEN (SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss))=0 THEN '--'
ELSE ROUND(ABS((SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss)))/2,1) END GB,
ROUND((SUM(Win)/SUM(Win+Loss)*100),2) AS Percentage
FROM WinsLosses AS R
GROUP BY TeamId
ORDER By Won DESC
) R ON T.Id = R.TeamId
ORDER BY R.PF DESC, T.SchoolName


And my WinsLosses view is:



select 
`Schedule`.`HomeTeamId` AS `TeamId`,
(case when (`Schedule`.`HomeTeamFinal` > `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`HomeTeamFinal` < `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`HomeTeamFinal` AS `PtsFor`,
`Schedule`.`AwayTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`HomeTeamFinal` != '0') and (`Schedule`.`AwayTeamFinal` != '0'))

union all

select
`Schedule`.`AwayTeamId` AS `TeamId`,
(case when (`Schedule`.`AwayTeamFinal` > `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`AwayTeamFinal` < `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`AwayTeamFinal` AS `PtsFor`,
`Schedule`.`HomeTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`AwayTeamFinal` != '0') and (`Schedule`.`HomeTeamFinal` != '0'))


I've been trying to figure this out for a couple days and am stuck. How would you best go about doing a streak with this database schema.










share|improve this question














bumped to the homepage by Community 11 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 2





    If the sequence is W,W,W,L,W,W -- Is that a W3 (the longest), or W2 (leading up to 'now')?

    – Rick James
    Aug 25 '17 at 15:50











  • Would be great if you included a data sample and the expected result for it.

    – Andriy M
    Aug 26 '17 at 15:34














0












0








0








I have a table Schedule for a local high school football conference. This is in MySQL. My goal is to include the "streak" for each team. If a team wins 2 games in a row the streak is W2, or if a team loses 4 games in a row, the streak would be L4.



Here's my table schema:



CREATE TABLE `Schedule` (
`ScheduleId` int(10) NOT NULL auto_increment COMMENT 'Schedule Id',
`SportId` int(11) NOT NULL COMMENT 'Sport Id',
`HomeTeamId` int(10) NOT NULL COMMENT 'Home Team Id',
`AwayTeamId` int(11) NOT NULL COMMENT 'Away Team Id',
`StartTime` datetime NOT NULL COMMENT 'Start Time of Event',
`HomeTeamFinal` double default NULL COMMENT 'Final Score of Home Team',
`AwayTeamFinal` double default NULL COMMENT 'Final Score of Away Team',
`IsRegularSeason` bit(1) NOT NULL default b'1',
PRIMARY KEY (`ScheduleId`)
)


I currently have a "Standings" query that shows the Won, Loss, Total, PF, PA, Percentage and Games Behind or each team. However, with this, I wanted to include the streak of each team.



My Standings SQL is as follows:



SELECT  T.SchoolName, R.Won AS W, R.Lost AS L, R.Total AS T, R.PF, R.PA, R.GB, R.Percentage AS P
FROM Teams AS T
INNER JOIN (
SELECT TeamId,
SUM(Win) As Won,
SUM(Loss) as Lost,
SUM(Win+Loss) as Total,
PtsFor AS PF,
PtsAgainst AS PA,
CASE WHEN (SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss))=0 THEN '--'
ELSE ROUND(ABS((SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss)))/2,1) END GB,
ROUND((SUM(Win)/SUM(Win+Loss)*100),2) AS Percentage
FROM WinsLosses AS R
GROUP BY TeamId
ORDER By Won DESC
) R ON T.Id = R.TeamId
ORDER BY R.PF DESC, T.SchoolName


And my WinsLosses view is:



select 
`Schedule`.`HomeTeamId` AS `TeamId`,
(case when (`Schedule`.`HomeTeamFinal` > `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`HomeTeamFinal` < `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`HomeTeamFinal` AS `PtsFor`,
`Schedule`.`AwayTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`HomeTeamFinal` != '0') and (`Schedule`.`AwayTeamFinal` != '0'))

union all

select
`Schedule`.`AwayTeamId` AS `TeamId`,
(case when (`Schedule`.`AwayTeamFinal` > `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`AwayTeamFinal` < `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`AwayTeamFinal` AS `PtsFor`,
`Schedule`.`HomeTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`AwayTeamFinal` != '0') and (`Schedule`.`HomeTeamFinal` != '0'))


I've been trying to figure this out for a couple days and am stuck. How would you best go about doing a streak with this database schema.










share|improve this question














I have a table Schedule for a local high school football conference. This is in MySQL. My goal is to include the "streak" for each team. If a team wins 2 games in a row the streak is W2, or if a team loses 4 games in a row, the streak would be L4.



Here's my table schema:



CREATE TABLE `Schedule` (
`ScheduleId` int(10) NOT NULL auto_increment COMMENT 'Schedule Id',
`SportId` int(11) NOT NULL COMMENT 'Sport Id',
`HomeTeamId` int(10) NOT NULL COMMENT 'Home Team Id',
`AwayTeamId` int(11) NOT NULL COMMENT 'Away Team Id',
`StartTime` datetime NOT NULL COMMENT 'Start Time of Event',
`HomeTeamFinal` double default NULL COMMENT 'Final Score of Home Team',
`AwayTeamFinal` double default NULL COMMENT 'Final Score of Away Team',
`IsRegularSeason` bit(1) NOT NULL default b'1',
PRIMARY KEY (`ScheduleId`)
)


I currently have a "Standings" query that shows the Won, Loss, Total, PF, PA, Percentage and Games Behind or each team. However, with this, I wanted to include the streak of each team.



My Standings SQL is as follows:



SELECT  T.SchoolName, R.Won AS W, R.Lost AS L, R.Total AS T, R.PF, R.PA, R.GB, R.Percentage AS P
FROM Teams AS T
INNER JOIN (
SELECT TeamId,
SUM(Win) As Won,
SUM(Loss) as Lost,
SUM(Win+Loss) as Total,
PtsFor AS PF,
PtsAgainst AS PA,
CASE WHEN (SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss))=0 THEN '--'
ELSE ROUND(ABS((SELECT SUM(Win-Loss) As WLSpan FROM WinsLosses GROUP BY TeamId Order By Win DESC LIMIT 1)-(SUM(Win)-SUM(Loss)))/2,1) END GB,
ROUND((SUM(Win)/SUM(Win+Loss)*100),2) AS Percentage
FROM WinsLosses AS R
GROUP BY TeamId
ORDER By Won DESC
) R ON T.Id = R.TeamId
ORDER BY R.PF DESC, T.SchoolName


And my WinsLosses view is:



select 
`Schedule`.`HomeTeamId` AS `TeamId`,
(case when (`Schedule`.`HomeTeamFinal` > `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`HomeTeamFinal` < `Schedule`.`AwayTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`HomeTeamFinal` AS `PtsFor`,
`Schedule`.`AwayTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`HomeTeamFinal` != '0') and (`Schedule`.`AwayTeamFinal` != '0'))

union all

select
`Schedule`.`AwayTeamId` AS `TeamId`,
(case when (`Schedule`.`AwayTeamFinal` > `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Win`,
(case when (`Schedule`.`AwayTeamFinal` < `Schedule`.`HomeTeamFinal`) then 1 else 0 end) AS `Loss`,
`Schedule`.`AwayTeamFinal` AS `PtsFor`,
`Schedule`.`HomeTeamFinal` AS `PtsAgainst`
from `Schedule`
where ((`Schedule`.`AwayTeamFinal` != '0') and (`Schedule`.`HomeTeamFinal` != '0'))


I've been trying to figure this out for a couple days and am stuck. How would you best go about doing a streak with this database schema.







mysql






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Aug 24 '17 at 18:43









TurpTurp

1011




1011





bumped to the homepage by Community 11 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 11 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.










  • 2





    If the sequence is W,W,W,L,W,W -- Is that a W3 (the longest), or W2 (leading up to 'now')?

    – Rick James
    Aug 25 '17 at 15:50











  • Would be great if you included a data sample and the expected result for it.

    – Andriy M
    Aug 26 '17 at 15:34














  • 2





    If the sequence is W,W,W,L,W,W -- Is that a W3 (the longest), or W2 (leading up to 'now')?

    – Rick James
    Aug 25 '17 at 15:50











  • Would be great if you included a data sample and the expected result for it.

    – Andriy M
    Aug 26 '17 at 15:34








2




2





If the sequence is W,W,W,L,W,W -- Is that a W3 (the longest), or W2 (leading up to 'now')?

– Rick James
Aug 25 '17 at 15:50





If the sequence is W,W,W,L,W,W -- Is that a W3 (the longest), or W2 (leading up to 'now')?

– Rick James
Aug 25 '17 at 15:50













Would be great if you included a data sample and the expected result for it.

– Andriy M
Aug 26 '17 at 15:34





Would be great if you included a data sample and the expected result for it.

– Andriy M
Aug 26 '17 at 15:34










1 Answer
1






active

oldest

votes


















0














So I actually figured this out in Postgres and then translated, my apologies if I missed a bit of syntax. This will show the win/loss streak for every game. I did not take different sportids into account here.



create table `winloss`
(
`counter` int(10) auto_increment,
`teamid` int(10),
`starttime` datetime,
`iswin` int(10),
`winstreak` int(10),
`losestreak` int(10)
);

--enter all teams in a single row with if they won or lost, order by teamid and gametime
insert into winloss (teamid, starttime, iswin)
select hometeamid teamid, starttime, case when hometeamfinal>awayteamfinal
then 1 else 0 end iswin
from Schedule s
union all
select awayteamid teamid, starttime, case when hometeamfinal<awayteamfinal
then 1 else 0 end iswin
from Schedule s
order by teamid, starttime;

DECLARE wonlost_counter int;
DECLARE wonlost_teamid int;

DECLARE prevwonlost_counter int;
DECLARE prevwonlost_iswin int;
DECLARE prevwonlost_winstreak int;
DECLARE prevwonlost_losestreak int;

DECLARE i int := 1;
DECLARE endi int;

--how many are in the table
SELECT endi=MAX(counter) FROM winloss;

--at each row, determine if this win/loss is a streak and add on
WHILE (i <= endi) DO
SELECT wonlost_counter=counter, wonlost_teamid=teamid FROM winloss WHERE counter=i;

select prevwonlost_counter=counter, prevwonlost_iswin=iswin,
prevwonlost_winstreak=winstreak, prevwonlost_losestreak=losestreak
from winloss where counter = wonlost_counter-1 and teamid=wonlost_teamid;

UPDATE winloss
SET winstreak=
CASE WHEN iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=1 then prevwonlost_winstreak+1
when iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=0 then 1
when iswin=0 then 0
else 1
end,
losestreak=
CASE WHEN iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=0 then prevwonlost_losestreak+1
when iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=1 then 1
when iswin=1 then 0
else 1
end
WHERE counter = wonlost_counter;

i := i + 1;

END WHILE;

select * from winloss;





share|improve this answer























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "182"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f184291%2ffinding-a-sporting-team-streak-in-mysql%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    So I actually figured this out in Postgres and then translated, my apologies if I missed a bit of syntax. This will show the win/loss streak for every game. I did not take different sportids into account here.



    create table `winloss`
    (
    `counter` int(10) auto_increment,
    `teamid` int(10),
    `starttime` datetime,
    `iswin` int(10),
    `winstreak` int(10),
    `losestreak` int(10)
    );

    --enter all teams in a single row with if they won or lost, order by teamid and gametime
    insert into winloss (teamid, starttime, iswin)
    select hometeamid teamid, starttime, case when hometeamfinal>awayteamfinal
    then 1 else 0 end iswin
    from Schedule s
    union all
    select awayteamid teamid, starttime, case when hometeamfinal<awayteamfinal
    then 1 else 0 end iswin
    from Schedule s
    order by teamid, starttime;

    DECLARE wonlost_counter int;
    DECLARE wonlost_teamid int;

    DECLARE prevwonlost_counter int;
    DECLARE prevwonlost_iswin int;
    DECLARE prevwonlost_winstreak int;
    DECLARE prevwonlost_losestreak int;

    DECLARE i int := 1;
    DECLARE endi int;

    --how many are in the table
    SELECT endi=MAX(counter) FROM winloss;

    --at each row, determine if this win/loss is a streak and add on
    WHILE (i <= endi) DO
    SELECT wonlost_counter=counter, wonlost_teamid=teamid FROM winloss WHERE counter=i;

    select prevwonlost_counter=counter, prevwonlost_iswin=iswin,
    prevwonlost_winstreak=winstreak, prevwonlost_losestreak=losestreak
    from winloss where counter = wonlost_counter-1 and teamid=wonlost_teamid;

    UPDATE winloss
    SET winstreak=
    CASE WHEN iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=1 then prevwonlost_winstreak+1
    when iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=0 then 1
    when iswin=0 then 0
    else 1
    end,
    losestreak=
    CASE WHEN iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=0 then prevwonlost_losestreak+1
    when iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=1 then 1
    when iswin=1 then 0
    else 1
    end
    WHERE counter = wonlost_counter;

    i := i + 1;

    END WHILE;

    select * from winloss;





    share|improve this answer




























      0














      So I actually figured this out in Postgres and then translated, my apologies if I missed a bit of syntax. This will show the win/loss streak for every game. I did not take different sportids into account here.



      create table `winloss`
      (
      `counter` int(10) auto_increment,
      `teamid` int(10),
      `starttime` datetime,
      `iswin` int(10),
      `winstreak` int(10),
      `losestreak` int(10)
      );

      --enter all teams in a single row with if they won or lost, order by teamid and gametime
      insert into winloss (teamid, starttime, iswin)
      select hometeamid teamid, starttime, case when hometeamfinal>awayteamfinal
      then 1 else 0 end iswin
      from Schedule s
      union all
      select awayteamid teamid, starttime, case when hometeamfinal<awayteamfinal
      then 1 else 0 end iswin
      from Schedule s
      order by teamid, starttime;

      DECLARE wonlost_counter int;
      DECLARE wonlost_teamid int;

      DECLARE prevwonlost_counter int;
      DECLARE prevwonlost_iswin int;
      DECLARE prevwonlost_winstreak int;
      DECLARE prevwonlost_losestreak int;

      DECLARE i int := 1;
      DECLARE endi int;

      --how many are in the table
      SELECT endi=MAX(counter) FROM winloss;

      --at each row, determine if this win/loss is a streak and add on
      WHILE (i <= endi) DO
      SELECT wonlost_counter=counter, wonlost_teamid=teamid FROM winloss WHERE counter=i;

      select prevwonlost_counter=counter, prevwonlost_iswin=iswin,
      prevwonlost_winstreak=winstreak, prevwonlost_losestreak=losestreak
      from winloss where counter = wonlost_counter-1 and teamid=wonlost_teamid;

      UPDATE winloss
      SET winstreak=
      CASE WHEN iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=1 then prevwonlost_winstreak+1
      when iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=0 then 1
      when iswin=0 then 0
      else 1
      end,
      losestreak=
      CASE WHEN iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=0 then prevwonlost_losestreak+1
      when iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=1 then 1
      when iswin=1 then 0
      else 1
      end
      WHERE counter = wonlost_counter;

      i := i + 1;

      END WHILE;

      select * from winloss;





      share|improve this answer


























        0












        0








        0







        So I actually figured this out in Postgres and then translated, my apologies if I missed a bit of syntax. This will show the win/loss streak for every game. I did not take different sportids into account here.



        create table `winloss`
        (
        `counter` int(10) auto_increment,
        `teamid` int(10),
        `starttime` datetime,
        `iswin` int(10),
        `winstreak` int(10),
        `losestreak` int(10)
        );

        --enter all teams in a single row with if they won or lost, order by teamid and gametime
        insert into winloss (teamid, starttime, iswin)
        select hometeamid teamid, starttime, case when hometeamfinal>awayteamfinal
        then 1 else 0 end iswin
        from Schedule s
        union all
        select awayteamid teamid, starttime, case when hometeamfinal<awayteamfinal
        then 1 else 0 end iswin
        from Schedule s
        order by teamid, starttime;

        DECLARE wonlost_counter int;
        DECLARE wonlost_teamid int;

        DECLARE prevwonlost_counter int;
        DECLARE prevwonlost_iswin int;
        DECLARE prevwonlost_winstreak int;
        DECLARE prevwonlost_losestreak int;

        DECLARE i int := 1;
        DECLARE endi int;

        --how many are in the table
        SELECT endi=MAX(counter) FROM winloss;

        --at each row, determine if this win/loss is a streak and add on
        WHILE (i <= endi) DO
        SELECT wonlost_counter=counter, wonlost_teamid=teamid FROM winloss WHERE counter=i;

        select prevwonlost_counter=counter, prevwonlost_iswin=iswin,
        prevwonlost_winstreak=winstreak, prevwonlost_losestreak=losestreak
        from winloss where counter = wonlost_counter-1 and teamid=wonlost_teamid;

        UPDATE winloss
        SET winstreak=
        CASE WHEN iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=1 then prevwonlost_winstreak+1
        when iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=0 then 1
        when iswin=0 then 0
        else 1
        end,
        losestreak=
        CASE WHEN iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=0 then prevwonlost_losestreak+1
        when iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=1 then 1
        when iswin=1 then 0
        else 1
        end
        WHERE counter = wonlost_counter;

        i := i + 1;

        END WHILE;

        select * from winloss;





        share|improve this answer













        So I actually figured this out in Postgres and then translated, my apologies if I missed a bit of syntax. This will show the win/loss streak for every game. I did not take different sportids into account here.



        create table `winloss`
        (
        `counter` int(10) auto_increment,
        `teamid` int(10),
        `starttime` datetime,
        `iswin` int(10),
        `winstreak` int(10),
        `losestreak` int(10)
        );

        --enter all teams in a single row with if they won or lost, order by teamid and gametime
        insert into winloss (teamid, starttime, iswin)
        select hometeamid teamid, starttime, case when hometeamfinal>awayteamfinal
        then 1 else 0 end iswin
        from Schedule s
        union all
        select awayteamid teamid, starttime, case when hometeamfinal<awayteamfinal
        then 1 else 0 end iswin
        from Schedule s
        order by teamid, starttime;

        DECLARE wonlost_counter int;
        DECLARE wonlost_teamid int;

        DECLARE prevwonlost_counter int;
        DECLARE prevwonlost_iswin int;
        DECLARE prevwonlost_winstreak int;
        DECLARE prevwonlost_losestreak int;

        DECLARE i int := 1;
        DECLARE endi int;

        --how many are in the table
        SELECT endi=MAX(counter) FROM winloss;

        --at each row, determine if this win/loss is a streak and add on
        WHILE (i <= endi) DO
        SELECT wonlost_counter=counter, wonlost_teamid=teamid FROM winloss WHERE counter=i;

        select prevwonlost_counter=counter, prevwonlost_iswin=iswin,
        prevwonlost_winstreak=winstreak, prevwonlost_losestreak=losestreak
        from winloss where counter = wonlost_counter-1 and teamid=wonlost_teamid;

        UPDATE winloss
        SET winstreak=
        CASE WHEN iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=1 then prevwonlost_winstreak+1
        when iswin=1 and prevwonlost_counter is not null and prevwonlost_iswin=0 then 1
        when iswin=0 then 0
        else 1
        end,
        losestreak=
        CASE WHEN iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=0 then prevwonlost_losestreak+1
        when iswin=0 and prevwonlost_counter is not null and prevwonlost_iswin=1 then 1
        when iswin=1 then 0
        else 1
        end
        WHERE counter = wonlost_counter;

        i := i + 1;

        END WHILE;

        select * from winloss;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 25 '17 at 17:12









        indiriindiri

        2,016211




        2,016211






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f184291%2ffinding-a-sporting-team-streak-in-mysql%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Szabolcs (Ungheria) Altri progetti | Menu di navigazione48°10′14.56″N 21°29′33.14″E /...

            Discografia di Klaus Schulze Indice Album in studio | Album dal vivo | Singoli | Antologie | Colonne...

            How to make inet_server_addr() return localhost in spite of ::1/128RETURN NEXT in Postgres FunctionConnect to...