case语句

mwg9r5ms  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(316)

我对sql非常陌生,有一个关于足球数据库的问题,该数据库包含以下表格:

Create Table Team(
TId char(3) Primary Key,                       // One example for a TId is "GER". It is an abbrevation for the country
Country varchar(50) Not Null,
Coach varchar(50) Not Null
)

Create Table Match(
MId Integer Primary Key,                      // Every match has an ID
Date date Null,
Stadium varchar(100) Not Null,
Team1 char(3) Not Null,
Team2 char(3) Not Null,
Foreign Key(Team1) references Team(TId),
Foreign Key(Team2) references Team(TId)
);

Create Table Goal(
MId Integer Null,
TId char(3) Null,
Player varchar(100) Not Null,
Minute Integer Null,
Primary Key(MId, Minute),
Foreign Key(MId) references Match(MId),
Foreign Key(TId) references Team(TId)
);

我需要编写一个sql查询,返回所有比赛的列表,包括日期、球场和两队的进球数。应该是这样的

Select date, stadium, Team1, Count(Goals Team1), Team2, Count(Goals Team2) 

From match

...

我试着先开始计算一个团队的进球数,想用一个案例来说明,但没能做到:

Select s.SId, s.Team1,
Case When s.SId IN (Select distinct SId From Tor) Then Count(t.SId) 
Else "Not In"   
End As text
From Spiel s, Tor t, Team te
Where s.SId = t.SId
Group by s.SId

如果你知道怎么做我会很高兴的。提前谢谢。

6mzjoqzu

6mzjoqzu1#

使用 CTE 返回每场比赛和每支球队的总进球数。
然后加入 Match 最多2份 Team 和两份 CTE :

with cte as (
  select mid, tid, count(*) goals
  from Goal
  group by mid, tid
)  
select m.date, m.stadium,
  t1.tid team1, coalesce(c1.goals, 0) goals_1,
  t2.tid team2, coalesce(c2.goals, 0) goals_2
from `Match` m
inner join Team t1 on t1.tid = m.team1
inner join Team t2 on t2.tid = m.team2
left join cte c1 on c1.mid = m.mid and c1.tid = m.team1
left join cte c2 on c2.mid = m.mid and c2.tid = m.team2

相关问题