oraclf 复杂查询练习_【二】Sqlzoo 练习 复杂查询

这篇博客通过SQLZOO的练习题,详细讲解了如何使用SQL进行复杂查询,包括汇总分析、数据分组、指定条件和排序。重点探讨了标量子查询、子查询和关联子查询的区别与应用,提供了具体的示例,如找出欧洲人均GDP高于英国的国家、计算各国人口占德国比例等。同时,强调了在使用聚合函数时的注意事项,如COUNT()函数的使用区别。
摘要由CSDN通过智能技术生成

1.汇总分析;

2.对数据进行分组;

3.对分组结果指定条件;

4.对查询结果进行排序;

6e52520b2c0c69b9868d13cb55401948.png
  • 子查询、标量子查询、关联子查询三者的关系:

0516b161398b13fd7440029f83e1ccce.png

SQLZOO 部分练习题

标量子查询练习:

  1. Show the countries in Europe with a per capita GDP greater than 'United Kingdom'.
SELECT name FROM world
WHERE continent= 'Europe' 
AND GDP/population > (SELECT GDP/population FROM world WHERE name ='united kingdom')

用子查询查询某一个值,用于比较。

2.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'

74ae1ef785b0d8dd08ec9e940c91a067.png

创建一个合并字段concat(列名1,'符号',列名2)→输出:列名1符号列名2

Round 函数不写小数位数代表取整

子查询练习:

3.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 >ALL (SELECT gdp FROM world WHERE continent='europe' AND gdp>0)

ALL运算符是一个逻辑运算符,它将单个值与子查询返回的单列值集进行比较。必须以比较运算符开头,例如:>>=<<=<>=,后跟子查询。

关联子查询练习:

4.List each continent and the name of the country that comes first alphabetically.

错误:这样只有第一个国家
select distinct x.continent,y.name
from world x join (select name from world order by name
                limit 1) as y
on x.continent=y.continent
正确:
SELECT continent,name
FROM world AS x
WHERE x.name = (SELECT y.name FROM world AS y  
                
WHERE x.continent=y.continent
                
ORDER BY name
limit 1)

当只有部分信息需要分组,不能用自连接,只有name要排名,continent不需要,所以无法用自连接。

5.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 AS x
WHERE 25000000>all(SELECT population FROM world AS y
 
WHERE x.continent=y.continent
and population>0)

6. Somecountries 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 a
WHERE population/3>all(SELECT population FROM world b
WHERE a.continent=b.continent AND a.name <> b.name AND population>0)

注意

聚合函数 Sum count avg distinct

count():如果指定列名count(列名)则会忽略空值行,如果count(*)则不会忽略。

不能只写count()空白是error

List the continents that have a total population of at least 100 million.

SELECT continent
FROM world
GROUP BY continent
HAVING sum(population)>=100000000 ----过滤分组结果
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值