一.大纲
代码顺序:
二、实战
1.创建“按性别汇总”视图
1.1 #使用视图查询数据
2.子查询
2.1找出每个课程里成绩最低的学号
step2:先对课程分组,然后找到每个课程的最小值,最后找到相应的学号
step3:
#先对课程分组,然后找到每个课程的最小值
select min(成绩)
from score
group by 课程号;
#最后根据最低成绩找到相应的学号
select 学号,成绩
from score
where 成绩 in (
select min(成绩)
from score
group by 课程号
);
2.2哪些学生的成绩比课程0002的全部成绩里的任意一个高呢?
step2:找到课程0002里面的成绩,按照成绩使用> any(成绩)找到符合要求的学生学号
step3:
select 学号,成绩
from score
where 成绩 > any(
select 成绩
from score
where 课程号='0002');
2.3哪些学生的成绩比课程0002的全部成绩里都(all)高呢?
3 标量子查询
3.1#定义差生是<=60,优等生>80分,要求找出成绩在差生平均成绩和优等生平均成绩之间的学生学号和成绩
step2:先求出差生的平均成绩,和优等生的平均成绩,然后后根据between avg(差生) and avg( 优等生)查询出符合条件的学生学号和成绩
step3:
select 学号,成绩
from score
where 成绩 between (
select avg(成绩)
from score
where 成绩 <=60)
and
(
select avg(成绩)
from score
where 成绩>80);
4 关联子查询
4.1查找每个课程中大于对应课程平均成绩的学生
step2:先求出每门课程的平均分,然后找出成绩高于对应学科平均分的学生
step3:
拓展练习
练习链接:
SELECT within SELECT Tutorial/zhsqlzoo.netSELECT name FROM world
WHERE population >
(SELECT population FROM world
WHERE name='Russia')
2.第二道题题目要找的是国家名字,不是人均gdp
select name
from world
where continent='Europe' and
gdp/population >
(
select gdp/population
from world
where name='United Kingdom'
)
select name,continent
from world
where continent in
(
select continent
from world
where name='Argentina' or name='Australia'
)
order by name;
select name,population
from world
where population between
(select population
from world
where name='Canada'
)+1
and
(select population
from world
where name='Poland'
)-1
#此处用concat表示百分数%,round函数*100可以使小数变成整数
select name,concat(
round
(
population/(select population from world where name='Germany')*100,0)
,'%')
from world
where continent='Europe';
select name
from world
where gdp > all(
select gdp
from world
where continent='Europe'and gdp>0);#因为有些gdp是null,如果不加>0,出不了结果
SELECT continent, name, area
FROM world
WHERE area =any(
select max(area)
from world
where area>0
group by continent
);
#要求输出每个州按照首字母排序的第一个国家的州和名字。用<=就只能取到第一个国家
select continent,name
from world a
where name <=all(
select name
from world b
where a.continent=b.continent
group by continent
)
select name,continent,population
from world a
where 25000000>= all(
select population
from world b
where a.continent =b.continent
group by continent
)
select name,continent
from world a
where population > all
(
select 3*population
from world b
where a.continent=b.continent
and a.name<>b.name
group by continent
)