数据库
首页 > 数据库> > sqlzoo-day2

sqlzoo-day2

作者:互联网

【目标:完成子查询的部分】,明天完成聚合函数和NULL

--example 4
SELECT name FROM world
WHERE population > 
      (SELECT MAX(population) FROM world
        WHERE continent='Europe')
-- 也可以换成
SELECT name FROM world
WHERE population > ALL
      (SELECT population FROM world
        WHERE continent='Europe')
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

1. SELECT_within_SELECT

T5: 显示欧洲国家名称和人口,人口以德国人口的百分比做展示。使用ROUND设定小数位数,使用CONCAT增加%。

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

T6: 显示GDP比Europe全部国家都要高的国家,因为有国家的GDP=NULL,因此在使用ALL时,需要在子查询条件中加入GDP>0

SELECT name FROM world
WHERE gdp > (SELECT MAX(gdp) FROM world WHERE continent = 'Europe')
-- or use ALL
SELECT name FROM world
WHERE gdp > ALL(SELECT gdp FROM world WHERE continent = 'Europe' AND gdp>0)
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

T7: 展示每个州面积最大的国家,子查询与外部查询的数值调用,相同州的条件写法要注意。

SELECT continent, name, area FROM world x
  WHERE area >= ALL
    (SELECT area FROM world y
        WHERE y.continent=x.continent
          AND area>0)

 T8: 列出每个州中首字母排序在首位的国家,字母也可以用大于小于这种比较??

SELECT continent, name FROM world x
WHERE name <= ALL(SELECT name FROM world y
           WHERE x.continent = y.continent)

T9: 找出全部国家的人口数都≤25000000的州。对x.continent = y.continent理解不够,总是想先找到州再找人口条件的州,但上式等号就是找相同的州,在where语句只需控制人口。

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

T10: 这题也好难,[○・`Д´・ ○],找到国家人口是同州中其他国家人口的3倍或以上的国家。我的理解是同个州中人口最大的是次大的3倍或以上。然后开始思考如何用sql实现拿出最大和次大,结果看了人家答案,只要同州的国家name不一致的拿出来比较就好了。。。【关键大概是找到比较的范围,在什么对象中进行比较

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)

2.nobel的子查询

T4.颁发物理奖但是没有颁发化学奖的年份,直接将颁发化学奖年份去除,再加上物理奖的条件。之前是反过来想的,一直没有实现,要抓住关键条件。

SELECT DISTINCT yr FROM nobel
WHERE  subject = 'physics'AND yr NOT IN (SELECT yr FROM nobel WHERE subject = 'chemistry') 

T5.找到获奖人数多于12人的年份,直接在SELECT语句后加入GROUP BY会报错:'gisq.nobel.subject' isn't in GROUP BY,查资料说似乎要在SELECT中也出现该聚合字段。

SELECT * FROM nobel
WHERE yr IN (SELECT yr FROM nobel 
GROUP BY yr
HAVING COUNT(winner) > 12)

T6.最后一题直接写对了(*^▽^*)

SELECT winner, yr, subject FROM nobel 
WHERE winner IN 
(SELECT winner FROM nobel 
 GROUP BY winner
 HAVING COUNT(*)>1)
ORDER BY winner, yr

标签:name,day2,sqlzoo,world,WHERE,continent,SELECT,population
来源: https://blog.csdn.net/qq_40723301/article/details/120098211