当前位置: 首页 > news >正文

SQLZoo 练习与测试答案汇总(复杂题有最优解与其他解法分析、解题技巧)

sqlzoo网址:https://sqlzoo.net/wiki/SQL_Tutorial

做完题目全部正确的状态如下:

  

目录

一、SELECT basics 模块

二、SELECT from WORLD 模块

三、SELECT from Nobel 模块

四、SELECT in SELECT 模块

五、SUM and COUNT 模块

六、JOIN 模块

七、More JOIN 模块

八、Using Null 模块

九、Self Join 模块

十、Window function 模块


一、SELECT basics 模块

  • 最后还有对应小测试(quiz) 部分的所有答案
--1、The example uses a WHERE clause to show the population of 'France'. Note that strings should be in 'single quotes'; 
--Modify it to show the population of Germanyselect population from world
where name = 'Germany'--2、Checking a list The word IN allows us to check if an item is in a list. The example shows the name and population for the countries 'Brazil', 'Russia', 'India' and 'China'.
--Show the name and the population for 'Sweden', 'Norway' and 'Denmark'.SELECT name, population FROM world
WHERE name IN ('Sweden', 'Norway', 'Denmark');--3、Which countries are not too small and not too big? BETWEEN allows range checking (range specified is inclusive of boundary values). The example below shows countries with an area of 250,000-300,000 sq. km. Modify it to show the country and the area for countries with an area between 200,000 and 250,000.SELECT name, area FROM worldWHERE area BETWEEN 200000 AND 250000--quiz
1、C  2、E  3、E  4、C  5、C  6、C  7、C

二、SELECT from WORLD 模块

  • 最后还有对应小测试(quiz) 部分的所有答案
--1、Read the notes about this table. Observe the result of running this SQL command to show the name, continent and population of all countries.select name, continent, population from world--2、How to use WHERE to filter records. Show the name for the countries that have a population of at least 200 million. 200 million is 200000000, there are eight zeros.select name from world
where population >= 200000000;--3、Give the name and the per capita GDP for those countries with a population of at least 200 million.select name, gdp/population as "per capita GDP" from world
where population >= 200000000;--4、Show the name and population in millions for the countries of the continent 'South America'. Divide the population by 1000000 to get population in millions.select name, population/1000000 as "人口(百万)" from world
where continent = 'South America';--5、Show the name and population for France, Germany, Italyselect name, population from world
where name in ('France','Germany','Italy');--6、Show the countries which have a name that includes the word 'United'select name from world
where name like '%United%';--7、Two ways to be big: A country is big if it has an area of more than 3 million sq km or it has a population of more than 250 million.Show the countries that are big by area or big by population. Show name, population and area.select name,population,area from world
where population > 250000000 
or area > 3000000;--8、Exclusive OR (XOR). Show the countries that are big by area (more than 3 million) or big by population (more than 250 million) but not both. Show name, population and area.
--Australia has a big area but a small population, it should be included.
--Indonesia has a big population but a small area, it should be included.
--China has a big population and big area, it should be excluded.
--United Kingdom has a small population and a small area, it should be excluded.select name,population,area from world
where population > 250000000 
xor area > 3000000;--9、Show the name and population in millions and the GDP in billions for the countries of the continent 'South America'. Use the ROUND function to show the values to two decimal places. For Americas show population in millions and GDP in billions both to 2 decimal places.select name "国家名称",round(population/1000000,2) "人口(百万)",round(gdp/1000000000,2) "GDP(十亿)" from world
where continent = 'South America';--10、Show the name and per-capita GDP for those countries with a GDP of at least one trillion (1000000000000; that is 12 zeros). Round this value to the nearest 1000. Show per-capita GDP for the trillion dollar countries to the nearest $1000.select name, round(gdp/population/1000)*1000 as "per capita GDP" from world
where gdp >= 1000000000000;--11、Greece has capital Athens.
--Each of the strings 'Greece', and 'Athens' has 6 characters.
--Show the name and capital where the name and the capital have the same number of characters.
--You can use the LENGTH function to find the number of characters in a stringselect name, capital from world
where length(name)=length(capital);--12、The capital of Sweden is Stockholm. Both words start with the letter 'S'.
--Show the name and the capital where the first letters of each match. Don't include ------countries where the name and the capital are the same word.
--You can use the function LEFT to isolate the first character.
--You can use <> as the NOT EQUALS operator.select name, capital from world
where left(name,1)=left(capital,1)
and substring(name,2) != substring(capital,2);--13、Equatorial Guinea and Dominican Republic have all of the vowels (a e i o u) in the name. They don't count because they have more than one word in the name.
--Find the country that has all the vowels and no spaces in its name.
--You can use the phrase name NOT LIKE '%a%' to exclude characters from your results.
The query shown misses countries like Bahamas and Belarus because they contain at least one 'a'select name from world
where name not like '% %'
and name like '%a%'
and name like '%e%'
and name like '%i%'
and name like '%o%'
and name like '%u%';-- quiz
1、E  2、D  3、B  4、D  5、B  6、D  7、C  8、C

三、SELECT from Nobel 模块

  • 最后还有对应小测试(quiz) 部分的所有答案
--1、Change the query shown so that it displays Nobel prizes for 1950.select yr, subject, winner from nobel
where yr = 1950--2、Show who won the 1962 prize for literature.select winner from nobel
where yr = 1962
and subject = 'literature'--3、Show the year and subject that won 'Albert Einstein' his prize.select yr, subject from nobel
where winner = 'Albert Einstein'--4、Give the name of the 'peace' winners since the year 2000, including 2000.select winner from nobel
where yr >= 2000
and subject = 'peace'--5、Show all details (yr, subject, winner) of the literature prize winners for 1980 to 1989 inclusive.select yr, subject, winner from nobel
where yr between 1980 and 1989
and subject = 'literature '--6、Show all details of the presidential winners: Theodore Roosevelt、Thomas Woodrow Wilson、Jimmy Carter、Barack Obamaselect yr, subject, winner from nobel
where winner in ('Theodore Roosevelt','Thomas Woodrow Wilson','Jimmy Carter','Barack Obama')--7、Show the winners with first name Johnselect winner from nobel
where winner like 'John %'--8、Show the year, subject, and name of physics winners for 1980 together with the chemistry winners for 1984.select yr, subject, winner from nobel
where subject = 'physics' and yr = 1980
or subject = 'chemistry' and yr = 1984--9、Show the year, subject, and name of winners for 1980 excluding chemistry and medicineselect yr, subject, winner from nobel
where yr = 1980
and subject not in ('chemistry','medicine')--10、Show year, subject, and name of people who won a 'Medicine' prize in an early year (before 1910, not including 1910) together with winners of a 'Literature' prize in a later year (after 2004, including 2004)select yr, subject, winner from nobel
where subject = 'Medicine' and yr < 1910
or subject = 'Literature' and yr >= 2004--11、Find all details of the prize won by PETER GRÜNBERGselect yr, subject, winner from nobel
where winner = 'PETER GRÜNBERG'--12、Find all details of the prize won by EUGENE O'NEILLselect yr, subject, winner from nobel
where winner = "EUGENE O'NEILL"--13、List the winners, year and subject where the winner starts with Sir. Show the the most recent first, then by name order.select winner, yr, subject from nobel
where winner like 'Sir%'
order by yr desc, winner--14、The expression subject IN ('chemistry','physics') can be used as a value - it will be 0 or 1. Show the 1984 winners and subject ordered by subject and winner name; but list chemistry and physics last.select winner, subject from nobel
where yr= 1984
order by 
subject IN ('chemistry','physics'),
subject, winner--quiz
1、E  2、C  3、B  4、C  5、C  6、C  7、D

四、SELECT in SELECT 模块

  • 练习各种子查询
  • 最后还有对应小测试(quiz) 部分的所有答案
--1、List each country name where the population is larger than that of 'Russia'.select name from world
where population > (
select population from world
where name = 'Russia'
)--2、Show the countries in Europe with a per capita GDP greater than 'United Kingdom'.SELECT name as 'per capita GDP' FROM world
where continent = 'Europe'
and gdp/population > (
SELECT gdp/population FROM world
WHERE name='United Kingdom'
)--3、List the name and continent of countries in the continents containing either Argentina or Australia. Order by name of the country.SELECT name, continent FROM world
where continent in
(
select continent from world
where name in ('Australia','Argentina')
)
order by name--4、Which country has a population that is more than United Kingdom but less than Germany? Show the name and the population.select name, population from world
where population >
(select population from world
where name = 'United Kingdom')
and population <
(select population from world
where name = 'Germany')--5、Show the name and the population of each country in Europe. Show the population as a percentage of the population of Germany.select name, concat(round(population/(select population from world where name = 'Germany')*100),'%') as "percentage"
from world
where continent = 'Europe'--6、Which countries have a GDP greater than every country in Europe? [Give the name only.] (Some countries may have NULL gdp values)select name from world
where gdp >
(
select max(gdp) from world
where continent = 'Europe' and gdp is not null
)
and gdp is not null或者使用 all 函数select name from world
where gdp >
all(
select gdp from world
where continent = 'Europe' and gdp is not null
)
and gdp is not null--7、Find the largest country (by area) in each continent, show the continent, the name and the areaselect continent, name, area from world
where area in (
select max(area) from world
group by continent
)--8、List each continent and the name of the country that comes first alphabetically.select continent, min(name) from world
group by continent--9、Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name, continent and population.select  name, continent, population from world
where continent in (
select continent from world 
group by continent
having max(population) <= 25000000
)--10、Some countries have populations more than three times that of all of their neighbours (in the same continent). Give the countries and continents.select name, continent 
from world w1
where population > 3 *
(
select max(population) 
from world w2
where w1.continent = w2.continent
and w1.name != w2.name
)--quiz
1、C  2、B  3、A  4、D  5、B  6、B  7、B

五、SUM and COUNT 模块

  • 最后还有对应小测试(quiz) 部分的所有答案
--1、Show the total population of the world.select sum(population) from world--2、List all the continents - just once each.select distinct continent from world--3、Give the total GDP of Africaselect sum(gdp) from world
where continent = "Africa"--4、How many countries have an area of at least 1000000select count(name) from world
where area >= 1000000--5、What is the total population of ('Estonia', 'Latvia', 'Lithuania')select sum(population) from world
where name in ('Estonia', 'Latvia', 'Lithuania')--6、For each continent show the continent and number of countries.select continent, count(name) from world
group by continent--7、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--8、List the continents that have a total population of at least 100 million.select continent from world
group by continent
having sum(population) >= 100000000--quiz
CADEBEDD

六、JOIN 模块

  • join 其实就是 inner join 的缩写形式,也就是内连接,结果集中不包含一个表与另一个表不匹配的行,只保留表的交集部分
  • 介绍了隐式连接的写法
  • 涉及了左连接(left join)的用法,左连接属于外连接,保留左表的所有数据+其他表与左表的交集。因为有的查询不允许省略掉左表的任何数据,这种情况下就不能再用 join 了。
  • 最后还有对应小测试(quiz) 部分的所有答案
--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 distinct id, stadium, team1, team2
FROM goal join game
on goal.matchid = game.id  --或:on (matchid = id) 或 on (id = matchid) 顺序无所谓,指代明确即可
where game.id = 1012--简单的连接表查询其实也可以用隐式连接的写法,隐式连接默认的是inner join也就是join连接
--一定要记得写清楚连接条件,只要不犯缺少连接条件的错误,这个法子还是很好用的,新手练习题的难度级别够用了!
SELECT distinct id, stadium, team1, team2
FROM goal, game
where matchid = id
and id = 1012--3、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 goal.teamid = 'GER'--4、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 (id=matchid)
where goal.player like 'Mario%'--5、Show player, teamid, coach, gtime for all goals scored in the first 10 minutes gtime<=10select player, teamid, coach, gtime
from goal join eteam 
on (teamid=id)
where goal.gtime<=10--6、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 join eteam 
on (team1=eteam.id)  -- eteam.id 不能简化为 id,因为两个表都有id字段,会因指代不明而报错
where eteam.coach= 'Fernando Santos'--7、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 game.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.SELECT distinct player
FROM game JOIN goal 
ON matchid = id 
WHERE (team1='GER' or team2='GER')
and teamid != 'GER'--9、Show teamname and the total number of goals scored.SELECT teamname, count(player)
FROM eteam JOIN goal ON id=teamid
group by teamname--10、Show the stadium and the number of goals scored in each stadium.SELECT stadium, count(player)
FROM game JOIN goal ON id=matchid
group by stadium--11、For every match involving 'POL', show the matchid, date and the number of goals scored.SELECT matchid, mdate, count(player)
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(player)
FROM game JOIN goal ON matchid = id 
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.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 matchid = id
group by mdate, matchid, team1, team2
order by mdate, matchid, team1, team2;--quiz
DCAABCB

七、More JOIN 模块

  • 介绍了多表连接的用法
  • 最后还有对应小测试(quiz) 部分的所有答案
--1、List the films where the yr is 1962 [Show id, title]SELECT id, title
FROM movie
WHERE yr=1962--2、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--4、What id number does the actor 'Glenn Close' have?select id
from actor
where name = 'Glenn Close'--5、What is the id of the film 'Casablanca'select id
from movie
where title = 'Casablanca'--6、Obtain the cast list for 'Casablanca'.select name 
from casting 
join actor
on actorid = id
where movieid = (
select id from movie
where title = 'Casablanca'
)--7、Obtain the cast list for the film 'Alien'select name 
from casting
left join actor
on actorid = id
where movieid = (
select id from movie
where title = 'Alien'
)--8、List the films in which 'Harrison Ford' has appearedselect title
from movie
join casting
on movieid = id
where actorid = (
select id from actor
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 movie
join casting
on movieid = id
where actorid = (
select id from actor
where name = 'Harrison Ford'
)
and ord != 1--10、List the films together with the leading star for all 1962 films.select m.title, a.name
from movie m
join casting c on m.id = c.movieid
join actor a on a.id = c.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.--解1:(解1在简洁性以及性能上都优于解2,解2就当是练习多表连接了)
select yr, count(*) 
from movie m
join casting
on id = movieid
where actorid = (
select id from actor
where name = 'Rock Hudson')
group by yr
having count(*) > 2--解2:
select yr, count(*) 
from movie 
join casting on movie.id=movieid
join actor on actorid=actor.id
where name='Rock Hudson'
group by yr
having count(*) > 2--12、List the film title and the leading actor for all of the films 'Julie Andrews' played in.--解1:(解1更优,不要忘了加distinct,不然可能会有重复)
select distinct m.title, a2.name
from movie m
join casting c on c.movieid = m.id
join actor a on c.actorid = a.id and a.name = 'Julie Andrews'
join casting c2 on c2.movieid = m.id
join actor a2 on c2.actorid = a2.id and c2.ord = 1--解2:
select m.title, a.name
from movie m
join casting c on m.id = c.movieid
join actor a on a.id = c.actorid
WHERE m.id in 
(
select id
from movie
join casting on id = movieid
where actorid = (
select id from actor
where name='Julie Andrews'
)
)
and ord = 1--13、Obtain a list, in alphabetical order, of actors who've had at least 15 starring roles.--解1:(解1在语义和简洁性上更优。现代数据库的优化器会自动处理过滤条件的位置,因此两种解法在性能上基本无差异。)
select a.name
from actor a
join casting c on a.id = c.actorid and c.ord = 1
group by a.id, a.name
having count(*) >= 15
order by a.name--解2:
select a.name
from actor a
join casting c on a.id = c.actorid
where c.ord = 1
group by a.id, a.name
having count(*) >= 15
order by a.name--14、List the films released in the year 1978 ordered by the number of actors in the cast, then by title.select distinct title, count(actorid)
from movie
join casting on movieid = id
where yr = 1978
group by title
order by count(actorid) desc, title--15、List all the people who have worked with 'Art Garfunkel'.--解1:解1 比 解2 更优
/*
通过四次表连接直接关联数据:
a → c:找出当前演员的参演记录 movieid
c → c2:通过 movieid 关联同一电影的其他演员记录
c2 → a2:确保关联的演员不是当前演员(因为要找的是合作过的演员)
*/
select distinct a2.name
from actor a
join casting c on c.actorid = a.id and a.name = 'Art Garfunkel'
join casting c2 on c2.movieid = c.movieid
join actor a2 on a2.id = c2.actorid and a2.name != 'Art Garfunkel'--解2
select distinct name from actor
join casting on actorid = id
where movieid in (
select movieid from casting
join actor on  actorid = id and name = 'Art Garfunkel'
)
and name != 'Art Garfunkel'--quiz
CECBDCB

八、Using Null 模块

  • 介绍了 coalesce 函数的用法
  • 介绍了 case 语句的具体用法
  • 介绍了 ifnull 函数用法
  • 介绍了 if 函数用法
  • 最后还有对应小测试(quiz) 部分的所有答案
--1、List the teachers who have NULL for their department.select name from teacher
where dept <=> null  --或:where dept is null  或:where isnull(dept),注意不能对 null 使用=、!=、<> 这几个符号,否则运算结果也都是null,不能得到有效的运算结果--2、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--3、Use a different JOIN so that all teachers are listed.select teacher.name, dept.name
from teacher 
left join dept
on teacher.dept = dept.id--4、Use a different JOIN so that all departments are listed.select 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'--解1:使用 coalesce 函数,返回参数列表中第一个非 NULL 的值。
select name, coalesce(mobile, '07986 444 2266') as 'mobile number'
from teacher--解2:采用 case 语句
select name, case when mobile is not null then mobile else '07986 444 2266' end as 'mobile number'
from teacher--解3:采用 ifnull 函数
select name, ifnull(mobile, '07986 444 2266') as 'mobile number'
from teacher--解4:采用 if 函数
select name, if(mobile is not null, mobile, '07986 444 2266') as 'mobile 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 t.name, coalesce(d.name, 'None')
from teacher t
left join dept d
on t.dept = d.id--7、Use COUNT to show the number of teachers and the number of mobile phones.select count(id), 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 d.name, count(t.id)
from teacher t
right join dept d
on t.dept = d.id
group by d.id, d.name--9、Use CASE to show the name of each teacher followed by 'Sci' if the teacher is in dept 1 or 2 and 'Art' otherwise.-- 此处的left不可遗漏,因为要列出所有老师的名字,左表不可省略
-- 写 case 语句的技巧1:先把语句列出来 case when then else end,然后再填充内容
select t.name, case when d.id in (1, 2) then 'Sci' else 'Art' end
from teacher t
left join dept d
on t.dept = d.id--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.-- 写 case 语句的技巧2:这里涉及多个条件,那么就在 case when then else end 的基础上多加几组 when then 就行
select t.name, case when d.id in (1, 2) then 'Sci' when d.id = 3 then 'Art' else 'None' end
from teacher t
left join dept d
on t.dept = d.id--quiz
ECEBAA

九、Self Join 模块

  • 最后还有对应小测试(quiz) 部分的所有答案
--1、How many stops are in the database.select count(id) from stops--2、Find the id value for the stop 'Craiglockhart'select id from stops
where name = 'Craiglockhart'--3、Give the id and the name for the stops on the '4' 'LRT' service.select id, name from stops
join route on id = stop
where num = 4
and company = 'LRT'
order by pos  --这句是为了和答案一致另外加的,否则没有笑脸--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 (53, 149)
GROUP BY company, num
having COUNT(*) = 2--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.--解1:更优
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 and a.stop=53
join stops s
on b.stop = s.id and s.name = 'London Road'--解2:隐式连接(纯当练习隐式连接)
select a.company, a.num, a.stop, b.stop
from route a, route b, stops s
where a.company=b.company 
and a.num=b.num 
and a.stop=53 
and b.stop = s.id 
and s.name = 'London Road'--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'--解1:解1和解2都可以
select r1.company, r1.num, s1.name, s2.name
from route r1
join route r2 on r1.company=r2.company and r1.num=r2.num
join stops s1 on r1.stop=s1.id 
join stops s2 on r2.stop=s2.id 
where s1.name='Craiglockhart'
and s2.name='London Road'--解2
select r1.company, r1.num, s1.name, s2.name
from route r1
join route r2 on r1.company=r2.company and r1.num=r2.num
join stops s1 on r1.stop=s1.id and s1.name='Craiglockhart'
join stops s2 on r2.stop=s2.id and s2.name='London Road'--解3:练习隐式连接
select r1.company, r1.num, s1.name, s2.name
from route r1, route r2, stops s1, stops s2
where r1.company=r2.company and r1.num=r2.num
and r1.stop=s1.id and s1.name='Craiglockhart'
and r2.stop=s2.id and s2.name='London Road'--7、Give a list of all the services which connect stops 115 and 137 ('Haymarket' and 'Leith')--解1
select distinct r1.company, r1.num
from route r1
join route r2 on r1.company=r2.company and r1.num=r2.num
join stops s1 on r1.stop=s1.id and s1.id = 115
join stops s2 on r2.stop=s2.id and s2.id = 137--解2:练习隐式连接
select distinct r1.company, r2.num
from route r1, route r2, stops s1, stops s2
where r1.company=r2.company and r1.num=r2.num
and r1.stop=s1.id and s1.id=115 
and r2.stop=s2.id and s2.id=137--8、Give a list of the services which connect the stops 'Craiglockhart' and 'Tollcross'--解1
select distinct r1.company, r1.num
from route r1
join route r2 on r1.company=r2.company and r1.num=r2.num
join stops s1 on r1.stop=s1.id and s1.name='Craiglockhart'
join stops s2 on r2.stop=s2.id and s2.name='Tollcross'--解2:练习隐式连接
select distinct r1.company, r2.num
from route r1, route r2, stops s1, stops s2
where r1.company=r2.company and r1.num=r2.num
and r1.stop=s1.id and s1.name='Craiglockhart'
and r2.stop=s2.id and s2.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 distinct s1.name, r1.company, r1.num
from route r1
join route r2 on r1.company=r2.company and r1.num=r2.num
and r1.company = 'LRT'
join stops s1 on r1.stop=s1.id
join stops s2 on r2.stop=s2.id and s2.name='Craiglockhart'
group by r1.company, r1.num, r1.pos, s1.name  -- 这里添加的 r1.pos 项是为了和答案一致,否则没有笑脸--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./*
逻辑:
第一次连接,确定好出发站: ‘Craiglockhart’ 至 x 站
第二次连接,确定好终点站: y 站至 ‘Lochend’
最后将第一次连接得到的终点站和第二次连接得到的出发站对等一下,就是出发站和终点站之间要转的这个站,设置:x = y,即为 ‘Craiglockhart’ 至 ‘Lochend’ 要经过的中转站。 
*/
--每一次的连接只要复制粘贴前面写的代码,稍微改一下即可,表之间全部用 join 连接
select distinct r1.num, r1.company, s3.name, r3.num, r3.company
from route r1
join route r2 on r1.company=r2.company and r1.num=r2.num
join stops s1 on r1.stop=s1.id and s1.name='Craiglockhart '
join stops s2 on r2.stop=s2.id
join route r3
join route r4 on r3.company=r4.company and r3.num=r4.num
join stops s3 on r3.stop=s3.id
join stops s4 on r4.stop=s4.id and s4.name='Lochend'
where r2.stop = r3.stop
order by r1.num, r1.company, r1.pos, s3.name, r3.num, r3.company ---- 这里添加的 r1.pos 项是为了和答案一致,否则没有笑脸--quiz
CED

十、Window function 模块

  • 介绍了排序窗口函数 rank()over() 的用法
 --1、Show the lastName, party and votes for the constituency 'S14000024' in 2017.select lastname, party, votes
from ge
where constituency = 'S14000024' and yr = 2017
order by votes desc--2、You can use the RANK function to see the order of the candidates. If you RANK using (ORDER BY votes DESC) then the candidate with the most votes has rank 1.
--Show the party and RANK for constituency S14000024 in 2017. List the output by party/*
排序窗口函数 rank()over(): OVER()子句必须包含 ORDER BY
PARTITION BY 可选,对数据进行分组,进一步控制排名的范围。
RANK() OVER ([PARTITION BY 分组列1, 分组列2, ...]  -- 可选:按列分组ORDER BY 排序列1 [ASC|DESC], 排序列2 [ASC|DESC], ...  -- 必须:指定排序规则
)
*/
--此处的两个 order by 并不重复,一个用于或者排名,一个用于列出结果
select party, votes,
rank() over (order by votes desc) as posn
from ge
where constituency = 'S14000024' and yr = 2017
order by party--3、The 2015 election is a different PARTITION to the 2017 election. We only care about the order of votes for each year.
--Use PARTITION to show the ranking of each party in S14000021 in each year. Include yr, party, votes and ranking (the party with the most votes is 1).select yr, party, votes,
rank() over (partition by yr order by votes desc) as posn
from ge
where constituency = 'S14000021'
order by party, yr--4、Edinburgh constituencies are numbered S14000021 to S14000026.select constituency, party, votes,
rank()over(partition by constituency order by votes desc) as posn
from ge
where constituency between 's14000021' and 's14000026'
and yr  = 2017
order by posn, constituency--5、You can use SELECT within SELECT to pick out only the winners in Edinburgh.--子查询
select constituency, party from (
select constituency, party, votes,
rank()over(partition by constituency order by votes desc) as posn
from ge
where constituency between 's14000021' and 's14000026'
and yr  = 2017
) as cp
where cp.posn = 1--6、You can use COUNT and GROUP BY to see how each party did in Scotland. Scottish constituencies start with 'S'select party, count(*) from (
select party, constituency, votes, 
rank()over(partition by constituency order by votes desc) as posn
from ge
where yr  = 2017
) as pc
where pc.constituency like 'S%'
and pc.posn = 1
group by pc.party

http://www.dtcms.com/a/270843.html

相关文章:

  • 分类预测 | Matlab基于KPCA-ISSA-SVM和ISSA-SVM和SSA-SVM和SVM多模型分类预测对比
  • 打造自己的组件库(二)CSS工程化方案
  • Tensorflow的安装记录
  • 一天一道Sql题(day04)
  • 开源链动2+1模式与AI智能名片融合下的S2B2C商城小程序源码:重构大零售时代新生态
  • 华为静态路由配置
  • linux正向配置dns解析
  • 事件驱动架构
  • 汽车工业制造领域与数字孪生技术的关联性研究​
  • UI前端大数据处理性能评估与优化:基于负载测试的数据处理能力分析
  • 利用Wisdom SSH高效搭建CI/CD工作流
  • python Gui界面小白入门学习
  • # Shell 编程:从入门到实践
  • Android 系统默认代码,如何屏蔽相册分享功能
  • Android 组件内核
  • Go语言高级面试必考:切片(slice)你真的掌握了吗?
  • 设计模式(行为型)-责任链模式
  • golang条件编译:Build constraints
  • bash 判断 /opt/wslibs-cuda11.8 是否为软连接, 如果是,获取连接目的目录并自动创建
  • 基于Java+Maven+Testng+Selenium+Log4j+Allure+Jenkins搭建一个WebUI自动化框架(2)对框架加入业务逻辑层
  • 金融时间序列机器学习训练前的数据格式验证系统设计与实现
  • React对于流式数据和非流式数据的处理和优化
  • 【实战】Dify从0到100进阶--知识库相关模型原理
  • 【编程史】IDE 是谁发明的?从 punch cards 到 VS Code
  • 【Python基础】变量、运算与内存管理全解析
  • Vue的watch和React的useEffect
  • 第4章:实战项目一 打造你的第一个AI知识库问答机器人 (RAG)
  • SQL Server 2008R2 到 2012 数据库迁移完整指南
  • Debezium:一款基于CDC的开源数据同步工具
  • css支持if else