SQLZOO 答案—完整版(下)

简介: SQLZOO 答案—完整版(下)

SUM and COUNT


  1. Show the total population of the world.
SELECT SUM(population)
FROM world


  1. List all the continents - just once each.
select distinct continent from world


  1. Give the total GDP of Africa
select Sum(gdp) from world
where continent = 'Africa'


  1. How many countries have an area of at least 1000000
select count(*) from world 
where area >= 1000000


  1. What is the total population of (‘Estonia’, ‘Latvia’, ‘Lithuania’)
select sum(population) from world 
where name IN ('Estonia', 'Latvia', 'Lithuania')


  1. For each continent show the continent and number of countries.
select continent, count(name) from world 
group by continent 


  1. For each continent show the continent and number of countries with populations of at least 10 million.
select continent, count(name) from world 
where population >= 10000000
group by continent


  1. List the continents that have a total population of at least 100 million.
select continent from world 
group by continent 
having sum(population) >= 100000000


练习易错:

afa26344c38e45f195c673587aa05a3f.png


The JOIN operation


1、The first example shows the goal scored by a player with the last name ‘Bender’. The * says to list all the columns in the table - a shorter way of saying matchid, teamid, player, gtime

Modify it to show the matchid and player name for all goals scored by Germany. To identify German players, check for: teamid = ‘GER’

SELECT matchid, player FROM goal 
WHERE teamid = 'GER'

2、From the previous query you can see that Lars Bender’s scored a goal in game 1012. Now we want to know what teams were playing in that match.

Notice in the that the column matchid in the goal table corresponds to the id column in the game table. We can look up information about game 1012 by finding that row in the game table.

Show id, stadium, team1, team2 for just game 1012

SELECT id,stadium,team1,team2
FROM game 
WHERE id = 1012

3、You can combine the two steps into a single query with a JOIN.

SELECT *

FROM game JOIN goal ON (id=matchid)

The FROM clause says to merge data from the goal table with that from the game table. The ON says how to figure out which rows in game go with which rows in goal - the matchid from goal must match id from game. (If we wanted to be more clear/specific we could say

ON (game.id=goal.matchid)

The code below shows the player (from the goal) and stadium name (from the game table) for every goal scored.

Modify it to show the player, teamid, stadium and mdate for every German goal.

SELECT player,teamid, stadium, mdate 
FROM game 
JOIN goal ON (id=matchid)
WHERE teamid = 'GER'

4、Use the same JOIN as in the previous question.

Show the team1, team2 and player for every goal scored by a player called Mario player LIKE ‘Mario%’

SELECT team1, team2, player 
FROM game
JOIN goal ON (matchid=id)
WHERE player LIKE 'Mario%'

5、The table eteam gives details of every national team including the coach. You can JOIN goal to eteam using the phrase goal JOIN eteam on teamid=id

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 (id = teamid)
WHERE gtime<=10

6、To JOIN game with eteam you could use either

game JOIN eteam ON (team1=eteam.id) or game JOIN eteam ON (team2=eteam.id)

Notice that because id is a column name in both game and eteam you must specify eteam.id instead of just id

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

SELECT mdate, teamname 
FROM game g
JOIN eteam e ON g.team1 = e.id 
WHERE e.coach = 'Fernando Santos'
  1. List the player for every goal scored in a game where the stadium was ‘National Stadium, Warsaw’
SELECT player FROM goal
JOIN game ON matchid = id 
WHERE stadium = 'National Stadium, Warsaw'


8、The example query shows all goals scored in the Germany-Greece quarterfinal.

Instead show the name of all players who scored a goal against Germany.

HINT

Select goals scored only by non-German players in matches where GER was the id of either team1 or team2.

You can use teamid!=‘GER’ to prevent listing German players.

You can use DISTINCT to stop players being listed twice.

SELECT DISTINCT player 
FROM goal 
JOIN game ON matchid = id 
WHERE teamid != 'GER' 
AND (team1 = 'GER' or team2 = 'GER')
  1. Show teamname and the total number of goals scored.
    COUNT and GROUP BY
    You should COUNT(*) in the SELECT line and GROUP BY teamname
SELECT teamname, COUNT(*) 
FROM eteam 
JOIN goal ON id = teamid
GROUP BY teamname


  1. Show the stadium and the number of goals scored in each stadium.
SELECT stadium, COUNT(stadium)
FROM game a
JOIN goal b ON b.matchid = a.id
GROUP BY stadium


  1. For every match involving ‘POL’, show the matchid, date and the number of goals scored.
SELECT matchid, mdate, COUNT(matchid)
FROM game 
JOIN goal ON matchid = id 
WHERE (team1 = 'POL' OR team2 = 'POL')
GROUP BY matchid, mdate

12、For every match where ‘GER’ scored, show matchid, match date and the number of goals scored by ‘GER’

SELECT matchid, mdate, COUNT(*) 
FROM goal 
JOIN game ON id = matchid 
WHERE teamid = 'GER'
GROUP BY matchid, mdate


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.

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.

fb19ebc49544454e9566930d513da836.png

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


More JOIN operations


  1. List the films where the yr is 1962 [Show id, title]
SELECT id, title
FROM movie
WHERE yr=1962


  1. Give year of ‘Citizen Kane’.
SELECT yr FROM movie 
WHERE title = 'Citizen Kane'


3、List all of the Star Trek movies, include the id, title and yr (all of these movies include the words Star Trek in the title). Order results by year.

SELECT id, title, yr FROM movie 
WHERE title LIKE '%Star Trek%' 
ORDER BY yr
  1. What id number does the actor ‘Glenn Close’ have?
SELECT id FROM actor
WHERE name = 'Glenn Close'


  1. What is the id of the film ‘Casablanca’
SELECT id FROM movie 
WHERE title = 'Casablanca'


6、Obtain the cast list for ‘Casablanca’.

what is a cast list?

The cast list is the names of the actors who were in the movie.

Use movieid=11768, (or whatever value you got from the previous question)

select name from actor a 
join casting b on a.id=b.actorid 
where b.movieid=11768
  1. Obtain the cast list for the film ‘Alien’
SELECT a.name FROM casting c
JOIN actor a ON a.id = actorid 
JOIN movie m ON m.id = movieid
WHERE m.title = 'Alien'


  1. List the films in which ‘Harrison Ford’ has appeared
SELECT title 
FROM casting c
JOIN movie m ON m.id = movieid
JOIN actor a ON a.id = actorid
WHERE name = 'Harrison Ford'


9、List the films where ‘Harrison Ford’ has appeared - but not in the starring role. [Note: the ord field of casting gives the position of the actor. If ord=1 then this actor is in the starring role]

SELECT title 
FROM casting c
JOIN movie m ON m.id = movieid
JOIN actor a ON a.id = actorid
WHERE name = 'Harrison Ford'
AND c.ord != 1
  1. List the films together with the leading star for all 1962 films.
SELECT title, name 
FROM casting c
JOIN movie m ON m.id = movieid
JOIN actor a ON a.id = actorid
WHERE m.yr = '1962'
AND c.ord = 1


11、Which were the busiest years for ‘Rock Hudson’, show the year and the number of movies he made each year for any year in which he made more than 2 movies.

SELECT yr,COUNT(title) FROM movie 
JOIN casting ON movie.id=movieid
JOIN actor   ON actorid=actor.id
WHERE name='Rock Hudson'
GROUP BY yr
HAVING COUNT(title) > 2

12、List the film title and the leading actor for all of the films ‘Julie Andrews’ played in.

Did you get “Little Miss Marker twice”?

Julie Andrews starred in the 1980 remake of Little Miss Marker and not the original(1934).

Title is not a unique field, create a table of IDs in your subquery

SELECT title,name FROM casting a 
join movie b on a.movieid=b.id 
join actor c on a.actorid=c.id
WHERE movieid IN (
  SELECT movieid FROM actor c join casting a on c.id=a.actorid
  WHERE name='Julie Andrews') and ord=1
  1. Obtain a list, in alphabetical order, of actors who’ve had at least 15 starring roles.
select name from casting 
join actor on actorid = actor.id 
where ord = 1
group by name 
having count(*) >=15
order by name 


  1. List the films released in the year 1978 ordered by the number of actors in the cast, then by title.
select title, count(*) from movie 
join casting on movie.id = movieid 
where yr = 1978 
group by title 
order by count(actorid) desc, title


  1. List all the people who have worked with ‘Art Garfunkel’.
select distinct name from actor 
join casting on actorid = actor.id 
join movie on movieid = movie.id
where movieid in 
(
select movieid from casting 
join actor on actorid = actor.id
where name = 'Art Garfunkel'
)
and name != 'Art Garfunkel'        #不加此条件,会出现他自己的名字“Art Garfunkel”


select f.name from 
(select movieid from casting c 
join actor a on a.id=c.actorid 
where name='Art Garfunkel') as e 
join 
(select movieid, name from casting c 
join actor a on a.id=c.actorid 
where name!='Art Garfunkel') as f 
on e.movieid=f.movieid


Using Null


  1. List the teachers who have NULL for their department.
    Why we cannot use =

You might think that the phrase dept=NULL would work here but it doesn’t - you can use the phrase dept IS NULL

SELECT name FROM teacher
WHERE dept IS NULL


  1. Note the INNER JOIN misses the teachers with no department and the departments with no teacher.
SELECT teacher.name, dept.name
FROM teacher 
INNER JOIN dept ON (teacher.dept=dept.id)


  1. Use a different JOIN so that all teachers are listed.
SELECT DISTINCT teacher.name, dept.name FROM teacher 
LEFT JOIN dept ON teacher.dept = dept.id


  1. Use a different JOIN so that all departments are listed.
SELECT DISTINCT teacher.name, dept.name FROM teacher 
RIGHT JOIN dept ON teacher.dept = dept.id


5、Use COALESCE to print the mobile number. Use the number ‘07986 444 2266’ if there is no number given. Show teacher name and mobile number or ‘07986 444 2266’

SELECT 
name, 
COALESCE(mobile,'07986 444 2266') AS number 
FROM teacher

6、Use the COALESCE function and a LEFT JOIN to print the teacher name and department name. Use the string ‘None’ where there is no department.

SELECT teacher.name, COALESCE(dept.name,'None') 
FROM teacher 
LEFT JOIN dept ON dept.id = teacher.dept
  1. Use COUNT to show the number of teachers and the number of mobile phones.
SELECT COUNT(teacher.name),COUNT(mobile)
FROM teacher


8、Use COUNT and GROUP BY dept.name to show each department and the number of staff. Use a RIGHT JOIN to ensure that the Engineering department is listed.

SELECT dept.name, COUNT(teacher.name)
FROM dept 
LEFT JOIN teacher ON teacher.dept = dept.id       #LEFT JOIN
GROUP BY dept.name 

SELECT dept.name, COUNT(teacher.name)
FROM teacher 
RIGHT JOIN dept ON teacher.dept = dept.id       #RIGHT JOIN
GROUP BY dept.name


  1. Use CASE to show the name of each teacher followed by ‘Sci’ if the teacher is in dept 1 or 2 and ‘Art’ otherwise.
SELECT name,
CASE WHEN teacher.dept IS NOT NULL THEN 'Sci'     # 有dept.id只有1和2两个值,所以可以使用'IS NOT NULL'
     ELSE 'Art'
END
FROM teacher


SELECT name,
CASE WHEN teacher.dept IN (1,2) THEN 'Sci'
     ELSE 'Art'
END
FROM teacher


10、Use CASE to show the name of each teacher followed by ‘Sci’ if the teacher is in dept 1 or 2, show ‘Art’ if the teacher’s dept is 3 and ‘None’ otherwise.

SELECT name,
CASE WHEN teacher.dept IN (1,2) THEN 'Sci'
     WHEN teacher.dept = 3 THEN 'Art'
     ELSE 'None'
END
FROM teacher

Self join


  1. How many stops are in the database.
SELECT count(name) FROM stops


  1. Find the id value for the stop ‘Craiglockhart’
SELECT id FROM stops 
WHERE name = 'Craiglockhart'


  1. Give the id and the name for the stops on the ‘4’ ‘LRT’ service.
SELECT id, name FROM route JOIN stops ON (stop=id)
WHERE num= '4' AND company = 'LRT'


4、The query shown gives the number of routes that visit either London Road (149) or Craiglockhart (53). Run the query and notice the two services that link these stops have a count of 2. Add a HAVING clause to restrict the output to these two routes.

SELECT company, num, COUNT(*)
FROM route WHERE stop IN (149,53)
GROUP BY company, num
HAVING COUNT(*)>1

5、Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart, without changing routes. Change the query so that it shows the services from Craiglockhart to London Road.

SELECT a.company, a.num, a.stop, b.stop
FROM route a JOIN route b ON
  (a.company=b.company AND a.num=b.num)
WHERE a.stop=53 AND b.stop = 149     #由上题中确定C……和L……的stop

6、The query shown is similar to the previous one, however by joining two copies of the stops table we can refer to stops by name rather than by number. Change the query so that the services between ‘Craiglockhart’ and ‘London Road’ are shown. If you are tired of these places try ‘Fairmilehead’ against ‘Tollcross’

SELECT a.company, a.num, stopa.name, stopb.name
FROM route a JOIN route b ON
  (a.company=b.company AND a.num=b.num)
  JOIN stops stopa ON (a.stop=stopa.id)
  JOIN stops stopb ON (b.stop=stopb.id)
WHERE stopa.name='Craiglockhart'
AND stopb.name = 'London Road'
  1. Give a list of all the services which connect stops 115 and 137 (‘Haymarket’ and ‘Leith’)
SELECT distinct a.company, a.num FROM route a 
JOIN route b ON (a.company = b.company AND a.num = b.num)   # 注意条件是company和num相等
WHERE a.stop = 115
AND b.stop = 137


  1. Give a list of the services which connect the stops ‘Craiglockhart’ and ‘Tollcross’
SELECT a.company, a.num
FROM route a
JOIN route b ON (a.company = b.company AND a.num = b.num)
JOIN stops stopa ON a.stop = stopa.id
JOIN stops stopb ON b.stop = stopb.id
WHERE stopa.name = 'Craiglockhart' AND stopb.name = 'Tollcross'


9、Give a distinct list of the stops which may be reached from ‘Craiglockhart’ by taking one bus, including ‘Craiglockhart’ itself, offered by the LRT company. Include the company and bus no. of the relevant services.

SELECT stopb.name, a.company, a.num
FROM route a
JOIN route b ON (a.company = b.company AND a.num = b.num)
JOIN stops stopa ON a.stop = stopa.id
JOIN stops stopb ON b.stop = stopb.id
WHERE stopa.name = 'Craiglockhart'

10、Find the routes involving two buses that can go from Craiglockhart to Lochend.

Show the bus no. and company for the first bus, the name of the stop for the transfer,

and the bus no. and company for the second bus.

Hint

Self-join twice to find buses that visit Craiglockhart and Lochend, then join those on matching stops.

SELECT DISTINCT a.num, a.company, y.name,c.num, c.company
FROM route a 
JOIN route b ON (a.company = b.company AND a.num = b.num)
JOIN 
(route c JOIN route d ON (c.company = d.company AND c.num = d.num))
         JOIN stops x ON (a.stop = x.id)
         JOIN stops y ON (c.stop = y.id)
         JOIN stops z ON (d.stop = z.id)
WHERE x.name = 'Craiglockhart' 
AND z.name = 'Lochend' 
AND b.stop = c.stop
ORDER BY a.num, y.name, d.num


相关文章
|
算法 C++ 容器
(万字,细细阅读)竞赛算法入门必经算法模型(附带题目链接和模板)(上)
(万字,细细阅读)竞赛算法入门必经算法模型(附带题目链接和模板)(上)
50 0
|
存储 算法 决策智能
(万字,细细阅读)竞赛算法入门必经算法模型(附带题目链接和模板)(下)
(万字,细细阅读)竞赛算法入门必经算法模型(附带题目链接和模板)(下)
82 0
|
6月前
|
SQL 监控 大数据
DataGrip 面试题及答案整理,最新面试题
DataGrip 面试题及答案整理,最新面试题
175 0
|
6月前
|
前端开发 JavaScript 算法
前端面试题及答案整理
前端面试题及答案整理
500 0
|
6月前
|
前端开发 JavaScript 安全
前端面试题及答案
前端面试题及答案
|
6月前
|
XML 前端开发 JavaScript
2020 前端面试题总结大全 及 答案
2020 前端面试题总结大全 及 答案
|
6月前
|
算法
刷题专栏(十八):第一个错误的版本
刷题专栏(十八):第一个错误的版本
50 0
|
6月前
|
存储 安全 Java
精选Go高频面试题和答案汇总,阅读破万,收藏230+
精选Go高频面试题和答案汇总,阅读破万,收藏230+
|
SQL 关系型数据库 MySQL
SQLZOO 答案—完整版(上)
SQLZOO 答案—完整版(上)
428 0
|
数据可视化 数据挖掘 Linux
​分享小知识点,顺便考考ChatGPT
​分享小知识点,顺便考考ChatGPT
​分享小知识点,顺便考考ChatGPT