简体   繁体   中英

Case statement in a SQL query

I am pretty new in SQL and have a question regarding a football database with the following tables:

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)
);

I need to write a SQL query that gives me a back a list of all matches with the date, the stadium and the number of goals both teams scored. It should be something like

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

From match

...

I tried to start to count the goals for one team first and wanted to use a case statement but did not come that far:

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

I'd be pleased if you have any idea how to do that. Thanks in advance.

Use a CTE to return the total goals for each match and team.
Then join Match to 2 copies of Team and 2 copies of the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM