Sql server 使用group by子句连接表时出现问题
我有两张桌子,分别是Id和分数。样本数据 匹配IdSql server 使用group by子句连接表时出现问题,sql-server,join,Sql Server,Join,我有两张桌子,分别是Id和分数。样本数据 匹配Id > ID | HomeTeam |AwayTeam > 1 India Srilanka 2 Srilanka India 3 Pakistan India 得分 我需要写一个查询,它会给我 1 India (3) Srilanka (1) 2 Srilanka (0) India (1) 3 Pakistan (1) India (0) 谢谢大家! select
> ID | HomeTeam |AwayTeam
> 1 India Srilanka
2 Srilanka India
3 Pakistan India
得分
我需要写一个查询,它会给我
1 India (3) Srilanka (1)
2 Srilanka (0) India (1)
3 Pakistan (1) India (0)
谢谢大家!
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
.你试过自己写吗?我认为你的第二个表中的值是不正确的。我不理解你想要得到的结果。试着添加你所拥有的。我有,这是一个例子。但这就是我所拥有的数据。你试过自己写吗?我认为你的第二个表中的值是不正确的。我不理解你想要得到的结果。试着添加你所拥有的,我有,这是一个例子,但这是我所拥有的数据。。
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