I am building a Hockey Sports score and prediction system using PHP/MySQL. Below are the system design.
I have a GAMES table where two team numbers and their score in the game is present.The columns from this table are as below.
ID ---- TEAM1 ---- SCORE1 ---- TEAM2 ---- SCORE2
1 70 1 73 2
2 74 0 70 1
3 74 0 73 0
I also have a PICKS table where the details related to user's game predictions are present. Users can guess which team will win in a game and that data is stored in this table. The columns from this table are as below. Each user can guess only once for each game.
ID ---- GAME ---- USER ---- TEAM ---- POINT
1 1 1 70 1
2 2 1 70 1
3 3 1 73 1
3 1 2 70 1
Based on the above available data, I am trying to build up the result where each user (column USER) should be awarded the points(column POINT) for each correct guess. The guess can be validated based on the scores from GAMES table. The final output should be like as below.
USER ---- POINTS ---- CORRECT GUESS COUNT ---- WRONG GUESS COUNT
1 1 1 2
2 0 0 1
The columns "CORRECT GUESS COUNT" and "WRONG GUESS COUNT" represent the total number of correct guess and wrong guess done by the user.
I have created a SQL Fiddle for the above tables with some sample data.
http://sqlfiddle.com/#!2/8d469/4/0
EDIT:
Some more inforamtion are below. It's possible that a game can be a
draw.
In that case the score will be 0 for each team. When a game is
draw, users get no points.
SELECT p.user,
SUM(IF(g.id IS NOT NULL, p.point, 0)) As points,
SUM(IF(g.id IS NOT NULL, 1, 0)) Correct,
SUM(IF(g.id IS NULL, 1, 0)) Wrong
FROM Games g
RIGHT JOIN Picks p ON g.id = p.game AND
p.team = IF(g.score1 > g.score2 , g.team1, IF(g.score1 < g.score2, g.team2, NULL))
GROUP BY p.user;
SQL Fiddle (with your data)
You'll have to forgive me, if there is a more MySQL way to do it than this (background is Oracle/SQL Server):
SELECT
p.user
,sum(CASE
WHEN p.team = g.winner THEN point ELSE 0 END) points
,sum(CASE
WHEN p.team = g.winner THEN 1 ELSE 0 END) good_guess
,sum(CASE
WHEN p.team <> g.winner THEN 1 ELSE 0 END) bad_guess
FROM
picks p
INNER JOIN (
SELECT
id game_id
,CASE
WHEN score1 > score2 THEN team1
WHEN score2 > score1 THEN team2
ELSE -1 --no team_id as negative
END winner
FROM
games
) g
ON
g.game_id = p.game
GROUP BY
p.user
Related
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.
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;
For one of my sports related project, I need to show the record counts of teams.
Example: "Team 1" and "Team 2" has played 5 games. "Team 1" has won 3 times and "Team 2" has won 2 times. So the output should be (3-2).
Here is the table structure with some data.
ID ---- TEAM1 ---- SCORE1 ---- TEAM2 ---- SCORE2
1 70 1 73 2
2 74 0 70 1
3 74 2 73 1
4 73 1 70 0
The output should be something like:
TEAM1 ---- TEAM2---- RECORD
70 73 2-0
74 70 0-1
74 73 1-0
NOTE:
There will be always a winner and no game can be a draw.
In the output, the combination of team1 and team2 should be unique.
SQL Fiddle : http://sqlfiddle.com/#!2/4dead/1/0
The tricky thing here is dealing with the same teams playing in home and away fixtures. This can be worked around with (lots of) case statements.
The basic approach is to reformat the data so that the team with the lowest id appears first.
select
least(homeTeam, awayTeam) team1,
greatest(homeTeam, awayTeam) team2,
sum(case when awayTeam > homeTeam
then case when homeTeamScore > awayTeamScore then 1 else 0 end
else case when homeTeamScore > awayTeamScore then 0 else 1 end
end) team1Wins,
sum(case when hometeam > awayteam
then case when homeTeamScore > awayTeamScore then 1 else 0 end
else case when homeTeamScore > awayTeamScore then 0 else 1 end
end) team2Wins
from
games
group by
least(homeTeam, awayTeam),
greatest(homeTeam, awayTeam);
SQL Fiddle
or slightly more compact, but possibly harder to understand:
select
least(homeTeam, awayTeam) team1,
greatest(homeTeam, awayTeam) team2,
sum(case sign(awayTeam - homeTeam)
when sign(homeTeamScore - awayTeamScore) then 1
else 0 end) team1Wins,
sum(case sign(awayTeam - homeTeam)
when sign(awayTeamScore - homeTeamScore) then 1
else 0 end) team2Wins
from
games
group by
least(homeTeam, awayTeam),
greatest(homeTeam, awayTeam);
SQL Fiddle
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
I'm working with MySQL, and I have the following schema:
id school round score win loss tie
2 My School Name 1 10 1 0 0
3 My School Name 2 20 0 1 0
4 My School Name 3 30 1 0 0
5 My School Name 4 40 1 0 0
6 My School Name 5 50 1 0 0
7 My School Name 6 60 0 0 1
And I need the following output, grouped by school name
School Round1 Round2 Round3 Round4 Round5 Round6 wins losses ties
My School Name 10 20 30 40 50 60 4 1 1
So far I feel like I can use GROUP BY School and SUM(win) as wins to get most of the functionality out of it. The hard part, though, is to get those Round_ fields.
Does anyone know how to do this? Thanks in advance, any help would be much appreciated!
Edit: to clarify, I know I have 10 rounds exactly.
We can use a SELECT statement with a GROUP BY school to create a record for each school. The ties, wins, and losses columns are readily calculated with the SUM aggregate function, as you noted. To target a specific round, we can use some clever math (to avoid verbose conditional statements like the one CodeByMoonlight suggested):
If we want to target round R, we note that "round-R" is 0 only when round == R, otherwise it isn't 0. When we take the NOT of "round-R", 0 gets inverted to 1, while everything else gets set to 0. Now, if we multiply !(round-R) by the score of that round, it will give us 0 when the round is not R (as 0*score = 0) and it will give us "score" when the round is R (as 1*score = score). Next, when we take the SUM of this value over the columns, we add score when round=R and 0 otherwise, effectively giving us just the round R score.
Putting that all together gives:
SELECT school AS `School`,
SUM(!(round-1)*score) AS `Round1`,
SUM(!(round-2)*score) AS `Round2`,
SUM(!(round-3)*score) AS `Round3`,
SUM(!(round-4)*score) AS `Round4`,
SUM(!(round-5)*score) AS `Round5`,
SUM(!(round-6)*score) AS `Round6`,
SUM(!(round-7)*score) AS `Round7`,
SUM(!(round-8)*score) AS `Round8`,
SUM(!(round-9)*score) AS `Round9`,
SUM(!(round-10)*score) AS `Round10`,
SUM(win) AS `wins`,
SUM(loss) AS `losses`,
SUM(tie) AS `ties`
FROM `RoundScores` GROUP BY `school`
where RoundScores is the table in question.
EDIT:
If we do not want to manually add 10, we can use prepared statements :
# Store all the conditionals in a string:
# I was not able to to have round loop from 1 to 10, so I iterated over
# all distinct values of 'round' present in the table.
SET #s = "";
SELECT `round`, (#s := CONCAT( #s , "SUM(!(round-",round, ")*score) AS `Round",round, "`," )) FROM `RoundScores` GROUP BY `round`;
# Combine the conditionals from before with the rest of the statement needed.
SET #qry = CONCAT("SELECT school AS `School`,",#s,"SUM(win) AS `wins`,SUM(loss) AS `losses` FROM `RoundScores` GROUP BY `school`");
# Prepare and execute the statement.
PREPARE stmt1 FROM #qry;
EXECUTE stmt1;
TRY WITH UNION ( not tested)
SELECT SUM(win) AS wins, SUM(loss) AS losses, SUM(tie) AS ties
FROM table
GROUP BY (school)
UNION
SELECT score AS round1 FROM table WHERE round=1
UNION
SELECT score AS round2 FROM table WHERE round=2
.... AND so on..
SELECT School, Sum(Case
When Round = 1 Then Score
Else 0
End) AS Round1, Sum(Case
When Round = 2 Then Score
Else 0
End) AS Round2, Sum(Case
When Round = 3 Then Score
Else 0
End) AS Round3, Sum(Case
When Round = 4 Then Score
Else 0
End) AS Round4, Sum(Case
When Round = 5 Then Score
Else 0
End) AS Round5, Sum(Case
When Round = 6 Then Score
Else 0
End) AS Round6, Sum(Case
When Round = 7 Then Score
Else 0
End) AS Round7, Sum(Case
When Round = 8 Then Score
Else 0
End) AS Round8, Sum(Case
When Round = 9 Then Score
Else 0
End) AS Round9, Sum(Case
When Round = 10 Then Score
Else 0
End) AS Round10, Sum(Wins) AS Wins, Sum(Losses) AS Losses, Sum(Ties) AS Ties
FROM MyTable
GROUP BY School
Should work :)