数据库学习7-26

 

课堂练习

1.用相关子查询实现:查询每个部门工资最低的两个员工编号、姓名、工资。

 select empno,enamel,sal  from emp a  where 2>(select count(1) from emp b where a.deptno=b.deptno and a.sal>b.sal);  

2.查询每个部门工资前二。

 select *  from emp a  where 2>(select count(1) from emp b where a.deptno=b.deptno and a.sal<b.sal);

 

 select *  from emp a  where exists (select 1 from emp b where a.deptno=b.deptno and a.sal<b.sal having count(1)<2);

 

oracle

第八章

课后作业

1.用集合运算,列出不包含job为SALESMAN 的部门的部门号。  

select deptno from emp ;  minus  select deptno from emp where job='SALESMAN';

2.写一个联合查询,列出下面的信息:EMP表中所有雇员的名字和部门编号,不管他们是否属于任何部门。  DEPT表中的所有部门编号和部门名称,不管他们是否有员工。  

select ename,deptno ,null from emp  union  select deptno,dname ,null from dept;  

3.用集合运算查询出职位为SALESMAN和部门编号为10的人员编号、姓名、职位,不排除重复结果。

 select empno,ename,job from emp where job='SALESMAN'  union all  select empno,ename,job from emp where deptno=10;

4.用集合查询出部门为10和20的所有人员编号、姓名、所在部门名称。

 select empno,ename ,dept.dname from emp ,dept   where emp.deptno in(10,20) and emp.deptno=dept.deptno

 union  

select empno,ename,dept.dname from emp ,dept   where emp.deptno in(10,20) and emp.deptno=dept.deptno;

 

第九章

练习1  

1.用相关子查询实现:查询比自己所在职位平均工资高的员工姓名、职位。

 select ename,job  from emp a  where sal>(select avg(sal) from emp b where a.deptno=b.deptno);

 2.用相关子查询实现:查询员工工资为其部门最低工资的员工编号、姓名、工资。

 select empno,ename,sal  from emp a  where sal=(select min(sal) from emp b where a.deptno=b.deptno);

 3.用相关子查询实现:查询每个部门工资最低的两个员工编号、姓名、工资。

 select empno,ename,sal  from emp a  where 2>(select count(1) from emp b where a.deptno=b.deptno and a.sal<b.sal);

 

课后作业

 如下练习,使用相关子查询完成。

 1.写一个查询,来查找所有其薪水多于他所在部门的平均薪水的雇员,显示名字、部门号和部门的平均薪水,按平均薪水排序。

 select ename, deptno, avg(sal) avgsal  

 from emp a   where exists (select 1 from emp b where a.deptno = b.deptno having a.sal > avg(sal))          

group by ename,deptno

  order by avgsal;

 2.写一个查询显示所有雇员的 ID、名字和部门名字。

 select empno,ename,dname  from emp e,dept d  where e.deptno=d.deptno;

 3.写一个查询,显示那些在其所在的部门中有一个或多个比他来的更晚但薪水更高的同事名字。

 select ename  from emp a  where exists (select 1 from emp b where a.deptno=b.deptno and a.sal>b.sal and a.hiredate>b.hiredate);

posted on 2019-07-26 17:41  一只小白two  阅读(284)  评论(0编辑  收藏  举报