Rank standings table of soccer matches by H2H - mysql

Let me start explaining this with an example, I have a table with records of matches played in a soccer league, by using this table and its matches results am able to generate a standings table for the teams in this league via a mysql query.
Table [matches] (example)
--------------------------------------------------------
|id | hometeam |goalsfor|goalsagainst| awayteam |
--------------------------------------------------------
--------------------------------------------------------
| 8 | Real Madrid | 2 | 0 | Inter Milan |
--------------------------------------------------------
| 9 | Inter Milan | 3 | 3 | Real Madrid |
--------------------------------------------------------
Generated standings by query
Pos Team Pld W D L F A GD Pts
1 FC Barcelona 5 2 3 0 8 5 3 9
2 Inter Milan 6 2 2 2 11 10 1 8
3 Real Madrid 6 2 2 2 8 8 0 8
4 AC Milan 5 0 3 2 8 12 -4 3
The query:
select
team,
count(*) played,
count(case when goalsfor > goalsagainst then 1 end) wins,
count(case when goalsagainst> goalsfor then 1 end) lost,
count(case when goalsfor = goalsagainst then 1 end) draws,
sum(goalsfor) goalsfor,
sum(goalsagainst) goalsagainst,
sum(goalsfor) - sum(goalsagainst) goal_diff,
sum(
case when goalsfor > goalsagainst then 3 else 0 end
+ case when goalsfor = goalsagainst then 1 else 0 end
) score
from (
select hometeam team, goalsfor, goalsagainst from scores
union all
select awayteam, goalsagainst, goalsfor from scores
) a
group by team
order by score desc, goal_diff desc;
What I want to do is to order the standings based on Head to Head matches, so it would first order by points, then if there's a draw in points the second sorting would be to look at the two teams matches and compare who has more wins, or scored more than the other, then use that to sort the table.
By doing this as in the example Real Madrid will become ranked as 2nd and then Inter Milan as 3rd.
How can I achieve this?
I want to compare the two teams matches when they are equal in points, and use that to sort.
ORDER BY score DESC, h2h DESC; goal_diff DESC
Update: I ended going with a solution mix of sql and php, first I find equaled teams in rank, and then generate mini h2h standings for those team and update the rank based on it. I still see this doable with just sql, but with my heavy query its too complicated to implement with just sql, thats why I mixed with php in the implementation.

You need to process this in two steps. First, run the query above and store the results in a work table (call it work below). Then you need to get a tie breaker score for each team that is on the same score. Below, I join the matches table to the work table for each team, and ignore any where the work rows do not have the same score, as they are not important. Then give the team 1 if they won. Have to do it again for the other side. You might want to change this to the 3 for win, 1 for draw.
Sum these results up, join that result to the team row in work, and you have a tie break score for each row where where the score is the same.
You need to check what happens if you have many teams on the same score, and see if this is the result you want.
select w.*, b.hth
From work w
left outer join (
select team, SUM(hth) hth
from (
Select hometeam team, case when m.goalsfor > m.goalsagainst then 1 else 0 end hth
from matches m
inner join work w1 on m.hometeam = w1.team
inner join work w2 on m.awayteam = w2.team
where w1.score = w2.score
union all
Select awayteam team, case when m.goalsAgainst > m.goalsFor then 1 else 0 end hth
from matches m
inner join work w1 on m.hometeam = w1.team
inner join work w2 on m.awayteam = w2.team
where w1.score = w2.score
) a --all hth at same points
group by team
) b --summed to one row per team
on b.team = w.team
order by w.score desc, b.hth desc;

Related

MySQL Where Clause with Union All getting wrong results

I will preface this by saying I am still very much learning MySQL, and I am absolutely at that stage where I know just enough to be dangerous.
I have a database with data for scorekeeping for a sports league. We record wins/losses as either 1 or zero points. There is a night that has double play involved (meaning the players play twice in a single night, for 2 different formats). My data is structured like so (just a sample, I have hundreds of rows, over different formats):
ID
FID
WK
Type
HomeTeam
AwayTeam
HF1
HF2
AF1
AF2
1
44
1
PL
TM1
TM2
1
0
0
1
2
44
1
PL
TM3
TM4
0
0
1
1
3
44
2
PL
TM2
TM3
1
1
0
0
4
44
2
PL
TM4
TM1
0
1
1
0
5
44
3
PL
TM3
TM1
999
0
999
1
6
44
3
PL
Tm2
TM4
1
0
0
1
Where the 999 is used as a code number for us to know that the match hasn't yet been played, or the scoresheet hasn't been turned in to us for recordkeeping. (I use PHP to call these to a website for users to see what is going on, and am using an IF statement to convert that 999 to "TBD" on the website)
I can pull the Format 1 and Format 2 scores separately and get a listing just fine, but when I try to pull them together and get a total score, I am getting an incorrect count. I know the error lies with my WHERE Clause, but I've been banging my head trying to get it to work correctly, and I think I just need an extra set of eyes on this.
My current SQL Query is as follows:
SELECT Team,
SUM(TotalF1) AS TotalF1,
SUM(TotalF2) AS TotalF2,
SUM(TotalF1+TotalF2) AS Total
FROM ( ( SELECT HomeTeam AS Team,
HF1 AS TotalF1,
HF2 AS TotalF2
FROM tbl_teamscores
WHERE FID = 44
AND Type = 'PL'
AND HF1 != 999
AND HF2 != 999 )
UNION ALL
( SELECT AwayTeam,
AF1,
AF2
FROM tbl_teamscores
WHERE FID = 44
AND Type = 'PL'
AND AF1 != 999
AND AF2 != 999 )
) CC
GROUP BY Team
ORDER BY Total desc, Team ASC;
I am getting incorrect totals though, and I know the reason is because of those 999 designations, as the WHERE clause is skipping over ALL lines where either home or away score matches 999.
I tried separating it out to 4 separate Select Statements, and unioning them, but I just get an error when I do that. I also tried using Inner Join, but MySQL doesn't seem to like that either.
Edit to add DBFiddle with Real World Table Data and queries: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1d4d090b08b8280e734218ba32db6d88
An example of the problem can be observed when looking at the data for Player 10. The overall total should be 13, but I am only getting 12.
Any suggestions would be very helpful.
Thanks in advance!
You can use conditional aggregation:
SELECT Team,
SUM(CASE WHEN Total8 <> 999 THEN Total8 END) AS Total8,
SUM(CASE WHEN TotalLO <> 999 THEN TotalLO END) AS TotalLO,
SUM(CASE WHEN Total8 <> 999 THEN Total8 END) + SUM(CASE WHEN TotalLO <> 999 THEN TotalLO END) AS Total
FROM (
SELECT HomeTeam AS Team, Home8PTS AS Total8, HomeLOPTS AS TotalLO FROM tbl_teamscores WHERE FID = 44 AND Type = 'PL'
UNION ALL
SELECT AwayTeam, Away8PTS, AwayLOPTS FROM tbl_teamscores WHERE FID = 44 AND Type = 'PL'
) CC
GROUP BY Team
ORDER BY Team ASC;
or:
SELECT Team,
SUM(NULLIF(Total8, 999)) AS Total8,
SUM(NULLIF(TotalLO, 999)) AS TotalLO,
SUM(NULLIF(Total8, 999)) + SUM(NULLIF(TotalLO, 999)) AS Total
FROM (
SELECT HomeTeam AS Team, Home8PTS AS Total8, HomeLOPTS AS TotalLO FROM tbl_teamscores WHERE FID = 44 AND Type = 'PL'
UNION ALL
SELECT AwayTeam, Away8PTS, AwayLOPTS FROM tbl_teamscores WHERE FID = 44 AND Type = 'PL'
) CC
GROUP BY Team
ORDER BY Team ASC;
If you get nulls in the results then you should also use COALESCE():
SELECT Team,
COALESCE(SUM(NULLIF(Total8, 999)), 0) AS Total8,
COALESCE(SUM(NULLIF(TotalLO, 999)), 0) AS TotalLO,
COALESCE(SUM(NULLIF(Total8, 999)), 0) + COALESCE(SUM(NULLIF(TotalLO, 999)), 0) AS Total
FROM (
SELECT HomeTeam AS Team, Home8PTS AS Total8, HomeLOPTS AS TotalLO FROM tbl_teamscores WHERE FID = 44 AND Type = 'PL'
UNION ALL
SELECT AwayTeam, Away8PTS, AwayLOPTS FROM tbl_teamscores WHERE FID = 44 AND Type = 'PL'
) CC
GROUP BY Team
ORDER BY Team ASC;
See the demo.

SQL Query to Count who has the highest number of match victories

I'm creating a simple database which will allow me to track snooker results, producing head to head results between players. Currently I have 3 tables: (Player, Fixture, Result)
PlayerID PlayerName
1 Michael Abraham
2 Ben Mullen
3 Mark Crozier
FixtureID Date TableNo Group
1 07/12/2015 19:00:00 12 0
2 08/12/2015 12:00:00 9 0
ResultID FixtureID PlayerID FramesWon
1 1 1 3
2 1 3 1
3 2 1 2
4 2 3 5
As you can see in the Result table, Player1 has played Player3 two times, with Player1 winning the first match 3-1, and Player3 winning the second match 5-2. I would like a query which returns the total number of matches won between the two players. In this case the expected output should be:
PlayerID MatchesWon
1 1
3 1
Any help would be appreciated - I'm not even sure if this can be achieved via a query
I agree using windowing function would be best way to go if available (SQL Server for example)
Might be possible with a straight SQL method this way (given that the one having most wins in a "fixture" is the match winner)
SELECT PlayerId, FixtureID, Count(*) As MatchesWon
FROM Result r
WHERE r.Frameswon = (SELECT MAX(frameswon) FROM Result r2
WHERE
r.FixtureId = r2.FixtureId)
GROUP BY PlayerID,FixtureId
OR if can leave out the fixtureId, and filter for just the 2 players something like this one as well. with data given above should bring the sample results.
SELECT PlayerId, MatchesWon
FROM
(
SELECT FixtureID,PlayerId, Count(*) As MatchesWon
FROM Result r
WHERE r.Frameswon = (SELECT max(frameswon) FROM Result r2
WHERE
r.FixtureId = r2.FixtureId)
GROUP BY FixtureId,PlayerID
) s
WHERE
PlayerID IN (1,3)
Perhaps this would work for you:
select playerid, count(*) as matcheswon
from result as r1
where frameswon =
(
select max(frameswon)
from result as r2
where r2.fixtureid = r1.fixtureid
)
group by playerid
In a fiddle here: http://sqlfiddle.com/#!9/60821/2
This is the alternative you can try.
SELECT r.PlayerID, COUNT(r.PlayerID)
FROM (
SELECT FixtureID, MAX(FramesWon) AS FramesWon
FROM `result`
GROUP BY FixtureID
) win
INNER JOIN result r ON win.FixtureID = r.FixtureID AND win.FramesWon = r.FramesWon
GROUP By r.PlayerID

MySQL Winning Streak for every Player

I have a table with winner and loser statistics from a game:
id winner_id loser_id
1 1 2
2 1 2
3 3 4
4 4 3
5 1 2
6 2 1
7 3 4
8 3 2
9 3 5
10 3 6
11 2 3
12 3 6
13 2 3
I want a result table where i can find the highest winning streak of every player in the game. A streak of a player is broken, when he lost a game (player_id = loser_id). It should look like:
player_id win_streak
1 3
2 2
3 4
4 1
5 0
6 0
I tried many queries with user defined variables etc. but i can't find a solution. Thanks!
SQL Fiddle : http://sqlfiddle.com/#!9/3da5f/1
Is this the same as Alex's approach; I'm not quite sure, except that it seems to have one distinct advantage.... ;-)
SELECT player_id, MAX(CASE WHEN result = 'winner' THEN running ELSE 0 END) streak
FROM
( SELECT *
, IF(player_id = #prev_player,IF(result=#prev_result,#i:=#i+1,#i:=1),#i:=1) running
, #prev_result := result
, #prev_player:=player_id
FROM
( SELECT id, 'winner' result, winner_id player_id FROM my_table
UNION
SELECT id, 'loser', loser_id FROM my_table
) x
,
( SELECT #i:=1,#prev_result = '',#prev_player:='' ) vars
ORDER
BY x.player_id
, x.id
) a
GROUP
BY player_id;
I guess you should better to do that on php (or any other language you use) side.
But just to give you some idea and as experiment and example for some unique cases (hope it could be useful somewhere)
Here is my approach:
http://sqlfiddle.com/#!9/57cc65/1
SELECT r.winner_id,
(SELECT MAX(IF(winner_id=r.winner_id,IF(#i IS NULL, #i:=1,#i:=#i+1), IF(loser_id = r.winner_id, #i:=0,0)))
FROM Results r1
WHERE r1.winner_id = r.winner_id
OR r1.loser_id = r.winner_id
GROUP BY IF(winner_id=r.winner_id, winner_id,loser_id)) win_streak
FROM ( SELECT winner_id
FROM Results
GROUP BY winner_id
) r
It returns not all ids now but only who had ever win. So to make it better, probably you have user table. If so it would simplify a query. If you have no user table you need to union all somehow users who had never win.
You are welcome if any questions.

MySQL Joining two queries for sports team

I am trying to display a list of teams with the number of goals they have scored (and order them by greatest to smallest) but am having trouble with joining all the queries together
Table 1: Teams
teamid teamname
1 team1
2 team2
3 team3
Table 2: Results
id gameid teamid gf
1 1 1 5
2 2 1 3
3 1 2 0
4 2 2 2
5 3 3 0
What I'm trying to achieve
1. Team1 8
2. Team2 2
3. Team3 0
Get list of all teams
SELECT team.teamid, team.teamname
FROM teams team
Gets sum of goals for 1 team
SELECT COALESCE( SUM( gf ) , 0 ) goalsfor
FROM results
WHERE teamid = 1
Joining of queries
SELECT team.teamid,
team.teamname,
COALESCE(res.gf, 0) goalsfor
FROM teams team
LEFT JOIN
(SELECT COALESCE(SUM(res.gf), 0) goalsfor
FROM results res
GROUP BY teamid) res ON team.teamid = res.teamid
ORDER BY goalsfor DESC
Been stuck on joining the queries all day
SELECT teams.teamname, res.goals FROM teams JOIN (
SELECT COALESCE(SUM(results.gf),0) AS goals, results.teamid AS teamid FROM results
group by results.teamid) res
ON teams.teamid=res.teamid ORDER BY goals DESC;
My solution is:
SELECT t.id,
t.name,
SUM(r.gf) goalsfor
FROM team t
LEFT JOIN
results r ON t.id = r.teamId
GROUP BY t.id
ORDER BY goalsfor DESC
My result from my dummy table:
id name goalsfor
1 Apple 8
2 Banana 2
3 Carrot 0
I don't think you need COALESCE if you made your columns have a default of 0 and cannot be null.

MySQL - Select from two rows by a shared value where the query values are different

Very difficult to phrase this. Let me explain. I have a few tables: teams, games, and team_games. Team_games has a "standing" field which is 0'd by default. If standing is greater than 0, the game is finished and scores have been reported. I'm trying to come up with a query that will take two team IDs, and count the number of games they have in common where the standing is greater than zero.
Here's the table. So far I've done everything except for what I want.
Teams
---------------------
team_id team_name
---------------------
1 Test
2 Test 2
Games
---------------------
game_id start_time
---------------------
1 (unix)
2 -
3 -
Team Games
---------------------------------
game_id team_id standing
---------------------------------
1 1 1
1 2 2
2 1 2
2 2 1
3 1 1
3 2 2
So again, I want to capture just the rows where team_id is either 1 or 2, and the game id is the same, then count the unique game IDs.
So if I was looking for the number of games which were finished between team one and team two, the final result would be:
-----
COUNT
-----
3
SELECT COUNT(*) totalgames
FROM
(
SELECT Game_ID
FROM TeamGames
WHERE team_ID IN (1, 2) -- specify the teams here
GROUP BY Game_ID
HAVING COUNT(*) = 2 -- number of teams specified
AND SUM(standing = 0) = 0
) s
SQLFiddle Demo
OUTPUT
╔════════════╗
║ TOTALGAMES ║
╠════════════╣
║ 3 ║
╚════════════╝
i'm not sure but this may work
select count(distinct game_id) as games_number from Team_Games where (team_id = 1 or team_id = 2) and standing >= 1;
You can remove team from select clause and as well as group by, if you want.
SELECT T1.TEAM_ID, T2.TEAM_ID, COUNT(*)
FROM
TEAM_GAMES T1, TEAM_GAMES T2
WHERE T2.TEAM_ID <> T1.TEAM_ID
AND T2.GAME_ID = T2.GAME_ID
AND T1.STANDING > 0 AND T2.STANDING > 0
GROUP BY T1.TEAM_ID, T2.TEAM_ID