0

我有两个表 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)

谢谢 !

4

1 回答 1

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 与演示

于 2013-06-23T20:05:49.470 回答