1. 程式人生 > >sqlzoo-The JOIN operation學習筆記

sqlzoo-The JOIN operation學習筆記

在這裡插入圖片描述 game表:

id mdate stadium team1 team2
1001 8 June 2012 National Stadium, Warsaw POL GRE
1002 8 June 2012 Stadion Miejski (Wroclaw) RUS CZE
1003 12 June 2012 Stadion Miejski (Wroclaw) GRE CZE
1004 12 June 2012 National Stadium, Warsaw POL RUS

goal表:

matchid teamid player gtime
1001 POL Robert Lewandowski 17
1001 GRE Dimitris Salpingidis 51
1002 RUS Alan Dzagoev 15
1002 RUS Roman Pavlyuchenko 82

eteam表

id teamname coach
POL Poland Franciszek Smuda
RUS Russia Dick Advocaat
CZE Czech Republic Michal Bilek
GRE Greece Fernando Santos

5.Show player, teamid, coach, gtime for all goals scored in the first 10 minutes gtime<=10

SELECT player, teamid,coach,gtime
  FROM goal JOIN eteam ON teamid=id 
 WHERE gtime<=10

6.List the the dates of the matches and the name of the team in which ‘Fernando Santos’ was the team1 coach.

SELECT mdate,teamname FROM game JOIN eteam ON 
    eteam.id=game.team1 AND coach='Fernando Santos'

7.List the player for every goal scored in a game where the stadium was ‘National Stadium, Warsaw’

SELECT player from game JOIN goal ON id=matchid AND stadium='National Stadium,Warsaw'

13.List every match with the goals scored by each team as shown. This will use “CASE WHEN” which has not been explained in any previous exercises.

mdate team1 score1 team2 score2
1 July 2012 ESP 4 ITA 0
10 June 2012 ESP 1 ITA
10 June 2012 IRL 1 CRO 3

Notice in the query given every goal is listed. If it was a team1 goal then a 1 appears in score1, otherwise there is a 0. You could SUM this column to get a count of the goals scored by team1. Sort your result by mdate, matchid, team1 and team2.

SELECT mdate,
    team1,SUM(CASE WHEN teamid=team1 THEN 1 ELSE 0 END) AS score1,
    team2,SUM(CASE WHEN teamid=team2 THEN 1 ELSE 0 END) AS score2
    FROM game LEFT JOIN goal ON id=matchid GROUP BY mdate,