I have 2 table, one team and one match.
Team:
ID | Team_name |
---|---|
1 | PSG |
2 | OM |
ID is a Primary key
Matchs
ID_team_home | ID_team_away | goal_team_home | goal_team_away |
---|---|---|---|
1 | 2 | 5 | 4 |
2 | 1 | 6 | 1 |
ID_team_home and ID_team_away are foreign keys.
And the results i am aiming for is ONE query that doesn’t create a table but just select a sum of all of the goals of the teams
Team_name | Team_goals |
---|---|
PSG | 6 |
OM | 10 |
please help
I have tried many solutions, i have used sum,join,case when,if,subqueries nothing worked please help.
Most of the time it just sum the two rows and give me a totally unaccurate answer.
SELECT team.team_name, SUM(matchs.goal_team_home) as BPe, CASE WHEN matchs.ID_team_home=team.id THEN SUM(matchs.goal_team_home) WHEN matchs.ID_team_away=equipe.id THEN SUM(matchs.goal_team_away) END as test from matchs,team
WHERE matchs.ID_team_home=team.id or matchs.ID_team_away=team.id
GROUP BY equipe.Equipes
ORDER BY test
2
Answers
We can use a union approach combined with an outer aggregation:
The union brings all teams/goals inline into just two columns. We then aggregate by team on that intermediate result to get the team goals.
Join
team
tomatchs
with aLEFT
join (just in case there is a team without any row inmatchs
) and use conditional aggregation:See the demo.