SQL笔记1——SELECT

选择语句中常用的关键字

1.ORDER BY

知识点链接
题目链接

14题.
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 ('Physics','Chemistry'),subject,winner

写法二:

SELECT winner, subject
  FROM nobel
 WHERE yr=1984
 ORDER BY 
CASE WHEN subject IN ('Physics','Chemistry') THEN 1 ELSE 0 END,
subject,winner

The expression subject IN (‘Chemistry’,‘Physics’) can be used as a value - it will be false or true.
说明:写法二比写法一更标准,在写法一中,会默认将false转化为1,true转化为0

2.CONCAT

用来做连接操作的关键字
题目链接

Germany (population 80 million) has the largest population of the countries in Europe. Austria (population 8.5 million) has 11% of the population of Germany.
Show the name and the population of each country in Europe. Show the population as a percentage of the population of Germany.
Decimal places
You can use the function ROUND to remove the decimal places.
Percent symbol %
You can use the function CONCAT to add the percentage symbol.

SELECT name, CONCAT(
ROUND(population/(SELECT population FROM world WHERE name = 'Germany') * 100, 0), 
'%') 
FROM world 
WHERE continent = 'Europe'

3.GROUP BY, HAVING

说明:HAVING是在GROUP BY之后进行筛选

GROUP BY and HAVING. The HAVING clause is tested after the GROUP BY. You can test the aggregated values with a HAVING clause. Show the total population of those continents with a total population of at least half a billion.

题目分析
题目要求是展示出每个洲的总人口,条件是每个洲的总人口至少是5亿,那就需要对每个洲GROUP BY之后,再进行HAVING筛选

SELECT continent, SUM(population)
  FROM world
 GROUP BY continent
HAVING SUM(population)>500000000

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

特别注意下述写法是错误的,应该用HAVING

//错误写法
 SELECT region, SUM(area)
   FROM bbc 
  WHERE SUM(area) > 15000000 
  GROUP BY region
//正确写法
SELECT region, SUM(area)
FROM bbc
GROUP BY region
HAVING SUM(area) > 15000000

4.ALL

说明:ALL关键字,可用来获得大于所有值的结果(也就是信息中的最大值)或者小于也是一样
We can use the word ALL to allow >= or > or < or <=to act over a list. For example, you can find the largest country in the world, by population with this query:
举例:获得人口最多的国家名

SELECT name
  FROM world
 WHERE population >= ALL(SELECT population
                           FROM world
                          WHERE population>0)

注:You need the condition population>0 in the sub-query as some countries have null for population.

5.嵌套查询

说明:都在一个表中进行查询,给这个表起个别名用来区分
举例:

  1. Find the largest country (by area) in each continent, show the continent, the name and the area:
    题目链接
    查找出每个洲中area最大的国家
SELECT continent, name, area FROM world x
  WHERE area >= ALL
    (SELECT area FROM world y
        WHERE y.continent=x.continent
          AND area>0)

8.List each continent and the name of the country that comes first alphabetically.
题目链接

SELECT continent, name FROM world x 
WHERE name <= ALL(SELECT name FROM world y WHERE x.continent = y.continent)
ORDER 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.
题目链接
寻找那些每个国家的人口都不超过25000000的大洲。

SELECT name, continent, population FROM world x
WHERE 25000000 >= ALL(SELECT population FROM world y WHERE x.continent = y.continent)

10.Some countries have populations more than three times that of any of their neighbours (in the same continent). Give the countries and continents.
题目链接
查找那些在同一个洲内,国家的人口数大于其他国家人口三倍的国家

说明:这道题涉及到一个洲内的国家的人口进行比较,自己和自己比较不合理,所以要排除自己和自己比较的情况,不然没有一个符合要求的国家(因为自己永远不能大于自己的三倍)

SELECT name, continent FROM world x
WHERE population/3 > 
ALL(SELECT population FROM world y WHERE x.continent = y.continent AND x.name <> y.name)

select的嵌套应用

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=(SELECT stops.id FROM stops WHERE stops.name = 'Craiglockhart') 
  AND b.stop=(SELECT stops.id FROM stops WHERE stops.name = '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)
  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'

6.JOIN

JOIN ,COUNT, GROUP BY联合应用

11.For every match involving ‘POL’, show the matchid, date and the number of goals scored.
题目链接

SELECT matchid,mdate, COUNT(teamid)
  FROM game JOIN goal ON matchid = id 
 WHERE (team1 = 'POL' OR team2 = 'POL')
GROUP BY matchid, mdate

**说明:**上述需要计算出总的得分(这里出现在goal这个表中的那些teamid就是得分的队伍),这里不清楚用什么属性来分组,可以直接按照所列出的列种其他的列来分组

**特别注意:**GROUP BY 和 WHERE 的位置

笔记:

  1. 并不是按照什么属性进行GROUP BY 就按照什么属性进行COUNT,这里要看题目要求中要统计的什么信息
  2. GROUP BY 可以和 WHERE 在同一个SELECT语句中使用,也可以和HAVING在同一个语句中使用。
    和WHERE在一起用时放在WHERE之后;
    和HAVING 在一起用时放在HAVING之前(因为HAVING是针对GROUP BY的结果进行筛选)
    举例:
SELECT teamname, COUNT(*)
  FROM eteam JOIN goal ON teamid = id
 GROUP BY teamname
HAVING COUNT(*) < 3

//出现COUNT(*)的语句,是严格按照GROUP BY的属性进行统计

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 actor.name = 'Rock Hudson'
GROUP BY yr
HAVING COUNT(title) > 2

13.Obtain a list, in alphabetical order, of actors who’ve had at least 15 starring roles.
题目链接
查询结果是:至少获得过15次主演角色(ord=1)的演员

SELECT actor.name 
FROM actor JOIN casting ON (actorid = actor.id)
WHERE ord = 1
GROUP BY actorid
HAVING count(actorid) >= 15
ORDER BY actor.name

15.List all the people who have worked with ‘Art Garfunkel’.
题目链接
查找出那些和Art Garfunkel共同演过电影的演员

说明:在写查询语句时需要注意:这里是采用先选出Art Garfunkel演过的电影的id再列举出这些电影的演员,特别注意要排除掉演员Art Garfunkel自身

SELECT name FROM actor JOIN casting ON actor.id = casting.actorid
WHERE movieid IN 
(SELECT movie.id FROM movie JOIN casting ON (movie.id = movieid)
                            JOIN actor ON (actor.id = actorid)
WHERE name = 'Art Garfunkel')
AND name != 'Art Garfunkel'

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'

7.COALESCE

该关键字的作用是:将空值显示为默认值

COALESCE(x,y,z) = x if x is not NULL
COALESCE(x,y,z) = y if x is NULL and y is not NULL
COALESCE(x,y,z) = z if x and y are NULL but z is not NULL
COALESCE(x,y,z) = NULL if x and y and z are all NULL

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') FROM teacher

8.CASE

CASE WHEN condition1 THEN result1
WHEN condition2 THEN result2
……
END

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.
题目链接
如果老师是属于1或者2部门,那么在名字后面一列显示Sci,否则显示’Art’

SELECT name,
      CASE WHEN dept = 1 OR dept = 2 THEN 'Sci'           
           ELSE 'Art'
      END
FROM teacher

猜你喜欢

转载自blog.csdn.net/qq_31672701/article/details/104530392
今日推荐