Вы можете попробовать это
вход:
create table goals(
homeTeam varchar(10),
awayTeam varchar(10),
homeTeamGoals tinyint,
awayTeamGoals tinyint
);
insert into goals values('team1','team2',3,1),('team3','team4',1,2),('team1','team3',4,4),('team4','team2',0,1);
Выход:
select totalTeams.team as hometeam,
case when a.totalHomeGoals IS NULL THEN 0 ELSE a.totalHomeGoals END as totalHomeGoals,
case when a.totalHomeAgainstGoals IS NULL THEN 0 ELSE a.totalHomeAgainstGoals END as totalHomeAgainstGoals,
case when b.totalAwayGoals IS NULL THEN 0 ELSE b.totalAwayGoals END as totalAwayGoals,
case when b.totalAwayAgainstGoals IS NULL THEN 0 ELSE b.totalAwayAgainstGoals END as totalAwayAgainstGoals
from (select homeTeam as team from goals union select awayTeam from goals) as totalTeams
left join (select homeTeam as team, sum(homeTeamGoals) as totalHomeGoals,sum(awayTeamGoals) as totalHomeAgainstGoals from goals group by hometeam) as a on totalTeams.team=a.team
left join (select awayTeam as team,sum(awayTeamGoals) as totalAwayGoals,sum(homeTeamGoals) as totalAwayAgainstGoals from goals group by awayTeam) as b on totalTeams.team=b.team
order by hometeam ;