MySQL练习题(二)
9、取得薪水最高的前五名员工
select
e.ename,e.sal
from
emp e
order by
e.sal desc
limit 0,5;
10、取得薪水最高的第六到第十名员工
select
e.ename,e.sal
from
emp e
order by
e.sal desc
limit 5,5;
11、取得最后入职的 5 名员工
select ename,hiredate from emp order by hiredate desc limit 5;
12、取得每个薪水等级有多少员工
(1)求每个人的薪水等级
select e.ename,s.grade from emp e join salgrade s on e.sal between s.losal and s.hisal;
(2)将结果按照等级分组 求每个级别的数量 (可以不用视图,我这里只是想试一试)
create view view_empgrade as select e.ename,s.grade from emp e join salgrade s on e.sal between s.losal and s.hisal; #用结果创建一个视图
select grade,count(*) from view_empgrade group by grade;
13、面试题:(*)
有 3 个表 S(学生表),C(课程表),SC(学生选课表)
S(SNO,SNAME)代表(学号,姓名)
C(CNO,CNAME,CTEACHER)代表(课号,课名,教师)
SC(SNO,CNO,SCGRADE)代表(学号,课号,成绩)
问题:
13.1、找出没选过“黎明”老师的所有学生姓名。
select s.sname from s join sc on s.sno = sc.sno join c on c.cno = sc.cno where c.cteacher <> '黎明';
13.2、列出 2 门以上(含2 门)不及格学生姓名及平均成绩。
(1)先找出所有grade小于60的学生
select s.sname,sc.grade from s join sc on s.sno = sc.sno where sc.grade < 60;
(2)将这个结果按学生的姓名按照条件进行分组,并求平均值
select
s.sname,avg(sc.grade)
from
s
join
sc
on
s.sno = sc.sno
where
sc.grade < 60
group by
s.sname
having
count(*) >= 2;
13.3、既学过 1 号课程又学过 2 号课所有学生的姓名。
(1)先找出学过1号课程的学生
select s.sname from s join sc on s.sno = sc.sno where sc.cno = 1;
(2)再从上面结果查找学过2号课程的学生
select
s.sname
from
s
join
sc
on
s.sno = sc.sno
where
in(select s.sname from s join sc on s.sno = sc.sno where sc.cno = 1) and sc.cno = 1;
14、列出所有员工及领导的姓名
select
a.ename '员工', b.ename '领导'
from
emp a
left join
emp b
on
a.mgr = b.empno;
15、列出受雇日期早于其直接上级的所有员工的编号,姓名,部门名称
(1)找出受雇日期早于其直接上级的所有员工的编号,姓名
select
a.empno,a.ename,a.deptno
from
emp a
left join
emp b
on
a.mgr = b.empno
where
a.hiredate < b.hiredate;
(2)找出上面结果对应的部门名称
select
t.empno,t.ename,d.dname
from(
select
a.empno empno,a.ename ename,a.deptno deptno
from
emp a
left join
emp b
on
a.mgr = b.empno
where
a.hiredate < b.hiredate
) t
join
dept d
on
t.deptno = d.deptno;
16、 列出部门名称和这些部门的员工信息的同时列出那些没有员工的部门
select
e.*,d.dname
from
emp e
right join
dept d
on
e.deptno = d.deptno;
OPERATIONS这个部门没有员工