Take the following structure:
create table team (id int, name varchar(20));
insert into team values (1, 'H1'), (2, 'H2'), (3, 'H3');
create table game (id int, team1id int, team2id int);
insert into game values (11, 1, 2), (12, 1, 3), (13, 2, 3);
create table score (
id int,
gameid int,
team1score int,
team2score int
);
insert into score values
(21, 11, 5, 2),
(22, 12, 2, 5),
(23, 13, 0, 2);
Show game results (not yet an answer)
select
s.gameid,
t1.name as team1,
t2.name as team2,
team1score,
team2score
from score s
inner join game g on s.gameid = g.id
inner join team t1 on g.team1id = t1.id
inner join team t2 on g.team2id = t2.id;
The data is as follows:
gameid team1 team2 team1score team2score
11 H1 H2 5 2
12 H1 H3 2 5
13 H2 H3 0 2
Now give a rating (answer)
select
t.name,
sum(score) as goals
from team t
left join
(
select
t1.id as teamid,
sum(team1score) as score
from score s
inner join game g on s.gameid = g.id
inner join team t1 on g.team1id = t1.id
group by t1.id
union all
select
t2.id as teamid,
sum(team2score) as score
from score s
inner join game g on s.gameid = g.id
inner join team t2 on g.team2id = t2.id
group by t2.id
) t1 on t.id = t1.teamid
group by t.name
The result will look like this:
Name Goals
H1 7
H2 2
H3 7
Example: http://sqlfiddle.com/#!9/aa3cc/15
Although the example is for MySQL (since SQL Server Fiddle acted), the SQL statements will remain valid for SQL Server as well.