I currently have a list of all games played by team in which the list produces the team name, score, opponent name and score and either a W (Won), L (Lost) or D (Draw) which are all derived from my table "MatchDetails2017". What I want to do is display the cumulative win percentage after each game.
I have spent a few hours trying to find help online and have hit a brick wall.
SELECT Game, WL, ((SELECT COUNT(WL) FROM MatchDetails2017 WHERE Team = 'TeamName' AND WL = 'W')/COUNT(*))*100
FROM MatchDetails2017
WHERE Team = 'TeamName'
GROUP BY Game
For example I want the data to display like this...
Game|Result|Win%
1|W|100.00
2|W|100.00
3|W|100.00
4|L|75.00
5|D|60.00
6|W|66.67
This is my results I am currently getting...
1 W 5200.0000
2 W 5200.0000
3 W 5200.0000
4 L 5200.0000
5 D 5200.0000
6 W 5200.0000
To make this work the COUNT(*) to compute total games also needs to be over only the preceding games, so you need to bring it into your subquery. You also need to restrict the subquery to only games including and preceding the current one:
SELECT Game,
WL AS Result,
(SELECT SUM(WL = 'W') / COUNT(*) FROM MatchDetails2017 m2 WHERE m2.Game <= m1.Game AND m2.Team = m1.Team) * 100 AS `Win%`
FROM MatchDetails2017 m1
WHERE Team = 'TeamName'
Output:
Game Result Win%
1 W 100
2 W 100
3 W 100
4 L 75
5 D 60
6 W 66.6667
Demo on dbfiddle
Note that this query takes advantage of the fact that MySQL treats boolean values as either 1 or 0 in a numeric context, so we can SUM(WL = 'W') to get the total number of wins.
In MySQL 8+ we can try using COUNT as an analytic function:
SELECT
TeamID,
Game,
WL,
COUNT(CASE WHEN WL = 'W' THEN 1 END) OVER (PARTITION BY TeamId ORDER BY Game) /
COUNT(*) OVER (PARTITION BY TeamId) win_pct
FROM MatchDetails2017
ORDER BY
TeamID,
Game;
Related
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;
This question already has answers here:
Using LIMIT within GROUP BY to get N results per group?
(14 answers)
Closed 5 years ago.
This is different from the one marked as a double, I want to sum up top 5 for each team. The double post takes out for each of the results in separate rows.
I'm using this question now but it seems that SQL is randomly returning 5 of for exasmple 10 rows and sum up, not the top 5. Anyone has some input for me?
select team, sum(length) as totalScore
from
(SELECT t.*,
#num_in_group:=case when #team!=team then #num_in_group:=0 else #num_in_group:=#num_in_group+1 end as num_in_group,
#team:=team as t
FROM reg_catches t, (select #team:=-1, #num_in_group:=0) init
ORDER BY team asc) sub
WHERE sub.num_in_group<=4 and competition = 16 and team = 25
GROUP BY team
ORDER BY totalScore DESC;
I'm struggeling on a SQL question that I can't get my head around. My result-table looks like below, I'm trying to sum up the top 5 result for each team and limit the output to the top 3 highest ranked teams. Everything was working as expected until I added my last score in the result-table. The output of my SQL now is randomly for team 25. I've expected that to be 520..
team length competition
----------------------
26 70 16
25 70 16
25 95 16
25 98 16
25 100 16
25 100 16
25 100 16
25 122 16
Output:
team totalScore
---- -----------
25 122
26 70
Wanted output:
team totalScore
---- -----------
25 522
26 70
SELECT team, SUM(length) AS totalScore
FROM(
SELECT team, length
FROM table_result m
WHERE competition = 16 and (
SELECT COUNT(*)
FROM table_result mT
WHERE mT.team = m.team AND mT.length >= m.length
) <= 5) tmp
GROUP BY team
ORDER BY totalScore DESC Limit 3
Anyone has any ideas for me?
select team, sum(length)
from
(SELECT t.*,
#num_in_group:=case when #team!=team then #num_in_group:=0 else #num_in_group:=#num_in_group+1 end as num_in_group,
#team:=team as t
FROM test.table_result t, (select #team:=-1, #num_in_group:=0) init
ORDER BY team, length desc) sub
WHERE sub.num_in_group<=4
GROUP BY team
You should use a window function to accomplish this. Here's an example query:
SELECT team, SUM(length) AS totalScore FROM
(SELECT team,
length,
row_number() OVER (PARTITION BY team ORDER BY length desc) AS rowNumber
FROM table_result) tmp
WHERE rowNumber <= 5
AND competition = 16
GROUP BY team
ORDER BY totalScore DESC
LIMIT 3;
This query has two parts.
The inner query uses the row_number() window function to give every row an extra column that indicates its rank. PARTITION BY team says that the rank should be kept separately for each team, so that you end up being able to select the top n scores for every team.
The outer query uses a GROUP BY on the result of the inner query to take the SUM, per team, of all of the scores whose row number is less than or equal to 5 - in other words, the top 5 scores.
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
I am writing a hockey stat database. I have the need to calculate how many players were on the ice when a goal is scored.
I have set up the following sqlfiddle:
http://sqlfiddle.com/#!9/ed8fa
problem I am having is how to filter the results such that only goals that are scored at regular strength (shot type "reg") or goals that are scored while shorthanded (shot type "sh") count towards this total.
I need all players to be listed in the output, even if their number is zero. After finding the players "Plus rating", I will calculate each players "minus rating" and subtract the two. Once I figure out how to accurately find the "Plus rating", I should be able to figure out how to do the rest.
For the given data in the sqlfiddle, the desired output should be:
player_id Plus_count
20 1
21 0
22 2
23 1
24 1
25 0
26 1
27 1
28 1
29 0
30 0
31 2
32 1
33 0
I am having trouble figuring out how the join would work such that I can use where to filter out all goals that are "pp".
Thanks for any pointers you might be able to give...
adding what I have tried. This is from my dev db, so just slightly different from the sqlfiddle:
SELECT players.player_id as pp_id,
COALESCE(plus_players.count, 0) as Plus_Count
FROM players
LEFT JOIN (SELECT plus_players.fk_player_id, COUNT(*) as count
FROM plus_players
GROUP BY plus_players.fk_player_id) plus_players
ON plus_players.fk_player_id = players.player_id
left join (select * from shots_for
where regular_powerplay_shorthanded = 'reg' or regular_powerplay_shorthanded = 'sh') sf on sf.fk_player_id = players.player_id
union
SELECT players.player_id as pp_id,
COALESCE(plus_players.count, 0) as Plus_Count
FROM players
LEFT JOIN (SELECT plus_players.fk_player_id, COUNT(*) as count
FROM plus_players
GROUP BY plus_players.fk_player_id) plus_players
ON plus_players.fk_player_id = players.player_id
right join (select * from shots_for
where regular_powerplay_shorthanded = 'reg' or regular_powerplay_shorthanded = 'sh') sf2 on sf2.fk_player_id = players.player_id
left join goals_for on goals_for.fk_shot_for_id = sf2.shot_for_id
where regular_powerplay_shorthanded = 'reg' or regular_powerplay_shorthanded = 'sh'
you can see my various attempts above to use the where to eliminate the "pp" goals.
Hi I am trying to figure out a way of finding the largest winning streak for each member in my table. When the table was built, this was never in the plans to happen so is why Im seeking help on how I can achieve this.
My structure is as follows:
id player_id opponant_id won loss timestamp
If it is a persons game, the player id is their id. If they are being challenged by someone, their id is the opponant id and the won loss (1 or 0) is in relation to the player_id.
I want to find the greatest winning streak for each user.
Anyone have any ideas on how to do this with the current table structure.
regards
EDIT
here is some test data, where id 3 is the player in question:
id player_id won loss timestamp
1 6 0 1 2012-03-14 13:31:00
13 3 0 1 2012-03-15 13:10:40
17 3 0 1 2012-03-15 13:29:56
19 4 0 1 2012-03-15 13:37:36
51 3 1 0 2012-03-16 13:20:05
53 6 0 1 2012-03-16 13:32:38
81 3 0 1 2012-03-21 13:14:49
89 4 1 0 2012-03-21 14:01:28
91 5 0 1 2012-03-22 13:14:20
Give this a try. Edited to take into account loss rows
SELECT
d.player_id,
MAX(d.winStreak) AS maxWinStreak
FROM (
SELECT
#cUser := 0,
#winStreak := 0
) v, (
SELECT
player_id,
won,
timestamp,
#winStreak := IF(won=1,IF(#cUser=player_id,#winStreak+1,1),0) AS winStreak,
#cUser := player_id
FROM (
(
-- Get results where player == player_id
SELECT
player_id,
won,
timestamp
FROM matchTable
) UNION (
-- Get results where player == opponent_id (loss=1 is good)
SELECT
opponent_id,
loss,
timestamp
FROM matchtable
)
) m
ORDER BY
player_id ASC,
timestamp ASC
) d
GROUP BY d.player_id
This works by selecting all win/loses and counting the win streak as it goes through. The subquery is then grouped by player_id and the max winStreak as calculated as it looped through is output per-player.
It seemed to work nicely against my test dataset anyway :)
To do this more efficiently I would restructure, i.e.
matches (
matchID,
winningPlayerID,
timeStamp
)
players (
playerID
-- player name etc
)
matchesHasPlayers (
matchID,
playerID
)
Which would lead to an inner query of
SELECT
matches.matchID,
matchesHasPlayers.playerID,
IF(matches.winningPlayerID=matchesHasPlayers.playerID,1,0) AS won
matches.timestamp
FROM matches
INNER JOIN matchesHasPlayers
ORDER BY matches.timestamp
resulting in
SELECT
d.player_id,
MAX(d.winStreak) AS maxWinStreak
FROM (
SELECT
#cUser := 0,
#winStreak := 0
) v, (
SELECT
matchesHasPlayers.playerID,
matches.timestamp,
#winStreak := IF(matches.winningPlayerID=matchesHasPlayers.playerID,IF(#cUser=matchesHasPlayers.playerID,#winStreak+1,1),0) AS winStreak,
#cUser := matchesHasPlayers.playerID
FROM matches
INNER JOIN matchesHasPlayers
ORDER BY
matchesHasPlayers.playerID ASC,
matches.timestamp ASC
) d
GROUP BY d.player_id
SELECT * FROM
(
SELECT player_id, won, loss, timestamp
FROM games
WHERE player_id = 123
UNION
SELECT opponant_id as player_id, loss as won, won as loss, timestamp
FROM games
WHERE opponant_id = 123
)
ORDER BY timestamp
That will give you all the results for one player ordered by timestamp. Then you would need to loop those results and count winning records or else concatenate them all into a string and then use string functions to find your highest 11111 set in that string. That code will vary depending on the language you want to use, but logically those are the two choices.