第一题:列出每個國家的名字 name,當中人口 population 是高於俄羅斯’Russia’的人口。
SELECT name FROM world
WHERE population >
(SELECT population FROM world
WHERE name='Russia');
这题给出了代码,改了一下国家名就完事啦。
第二题:列出歐州每國家的人均GDP,當中人均GDP要高於英國’United Kingdom’的數值。
select name
from world
where continent = 'Europe'
and gdp/population > (select gdp/population from world where name = 'United Kingdom');
这题对我来说有两个坑:
- 人均GDP=gdp/population(QAQ显得我好没文化啊,这都不知道的样子)
- 列出的是
name
,最开始我选择列出的是人均GDP,就错了。(害,这是我的锅嘛。。好吧,是的)
第三题:在阿根廷Argentina 及 澳大利亞 Australia所在的洲份中,列出當中的國家名字 name 及洲分 continent 。按國字名字順序排序
select name, continent
from world
where continent in (select continent from world
where name in('Argentina','Australia'))
order by name;
这个数据表有点问题,那个名字都是按字母排列的,所以不用最后那句order by
也可以通过。
第四题:哪一個國家的人口比加拿大Canada的多,但比波蘭Poland的少?列出國家名字name和人口population 。
select name, population
from world
where population > (select population from world where name = 'Canada')
and population < (select population from world where name = 'Poland');
第五题:Germany德國(人口8000萬),在Europe歐洲國家的人口最多。Austria奧地利(人口850萬)擁有德國總人口的11%。
顯示歐洲的國家名稱name和每個國家的人口population。以德國的人口的百分比作人口顯示。
第一种想法是直接用8000万人,但显然是不对滴。
select name, concat(round((population/80000000)*100,2),'%') as population
from world
where continent ='Europe';
第二种是用子查询的方法:
select name, concat(round(population/(
select population from world
where name = 'Germany')*100,2),'%') as population
from world
where continent ='Europe';
这两种结果好像是一样的吧?没显示对错,先这样吧。
这题复习了concat()和round()函数。
all
词的用法小启发:
用法:>=、<=、>、<后再加all
例子中提到:查詢找到世界上最大的國家(以人口計算):
SELECT name
FROM world
WHERE population >= ALL(SELECT population
FROM world
WHERE population>0);
#子查询中的大于0,是为了排除null值。
这里也可以用来统计最高/最低工资,不需要使用orderby
后再用limit
函数来取数了。(去重的问题要另外考虑)
第六题:哪些國家的GDP比Europe歐洲的全部國家都要高呢? [只需列出 name 。] (有些國家的記錄中,GDP是NULL,沒有填入資料的。)
select name
from world
where gdp > all(select gdp from world
where continent ='Europe' and gdp>0);
第七题:在每一個州中找出最大面積的國家,列出洲份 continent, 國家名字 name 及面積 area。 (有些國家的記錄中,AREA是NULL,沒有填入資料的。)
SELECT continent, name, area FROM world x
WHERE area >= ALL(SELECT area FROM world y
WHERE y.continent=x.continent AND population>0);
第八题:列出洲份名稱,和每個洲份中國家名字按子母順序是排首位的國家名。(即每洲只有列一國)
SELECT continent, name
FROM world x
WHERE name <= ALL
(SELECT name
FROM world y
WHERE x.continent = y.continent);
这个地方x.continent = y.continent
其实类似group by
的作用,但是感觉没有group by
那么大限制。
第九题:找出洲份,當中全部國家都有少於或等於 25000000 人口. 在這些洲份中,列出國家名字name,continent 洲份和population人口。
SELECT name,continent,population
FROM world AS x
WHERE 25000000 >= ALL(SELECT population FROM world y
WHERE x.continent = y.continent)
AND population >0;
这里同理,用x.continent = y.continent
进行分组!!
第十题:有些國家的人口是同洲份的所有其他國的3倍或以上。列出 國家名字name 和 洲份 continent。
select name, continent
from world x
where population/3 > all( select population from world y
where x.continent = y.continent
and y.name != x.name)