Table with子句的表连接问题

时间:2013-06-23 19:51:36

标签: sql-server join

我有两个表Match_Id和Score。样本数据

Match_Id

> ID | HomeTeam  |AwayTeam  
> 1    India      Srilanka
  2    Srilanka   India 
  3    Pakistan   India

得分

Match_Id  Team    Score
 1        India    1
 1        India    1
 1       Srilanka  1
 3       Pakistan  1
 2        India    1
 1        India    1

我需要写一个能给我的查询

1  India   (3) Srilanka (1)
2 Srilanka (0) India  (1)
3 Pakistan (1) India  (0)

谢谢!

1 个答案:

答案 0 :(得分:3)

select m.ID
  , m.HomeTeam
  , HomeTeamScore = sum(case when m.HomeTeam = s.Team then 1 else 0 end)
  , m.AwayTeam
  , AwayTeamScore = sum(case when m.AwayTeam = s.Team then 1 else 0 end)
from Match_id m
  inner join Score s on m.ID = s.Match_Id
group by m.ID
  , m.HomeTeam
  , m.AwayTeam
order by m.ID

SQL Fiddle with demo