企业SQL面试复习与测试
二、企业SQL考核真题
数据表:
dept:
deptno(primary key), dname, loc
emp:
empno(primary key), ename, job, mgr(references emp(empno)), sal,
deptno(references dept(deptno))
1 列出emp表中各部门的部门号,最高工资,最低工资
select max(sal) as 最高工资,min(sal) as 最低工资,deptno from emp group by deptno;
2 列出emp表中各部门job 含’REP’的员工的部门号,最低工资,最高工资
select max(sal) as 最高工资,min(sal) as 最低工资,deptno as 部门号 from emp where job like '%REP%' group by deptno;
3 对于emp中最低工资小于7000的部门中job为'SA_REP'的员工的部门号,最低工资,最高工资
select max(sal) as 最高工资,min(sal) as 最低工资,deptno as 部门号 from emp b
where job='SA_REP' and 7000>(select min(sal) from emp a where a.deptno=b.deptno) group by b.deptno
4写出对上题的另一解决方法
(请补充)
select deptno,min(sal),max(sal)
from emp
where job = 'SA_REP' and deptno in (
select deptno
from emp
--group by deptno
having min(sal) < 7000
)
group by deptno
5根据部门号由高而低,工资由低而高列出每个员工的姓名,部门号,工资
select deptno as 部门号,ename as 姓名,sal as 工资 from emp order by deptno desc,sal asc
6 列出'Abel'所在部门中每个员工的姓名与部门号
select ename,deptno from emp where deptno = (select deptno from emp where ename = 'Abel')
(法二)
select ename,deptno
from emp e1
where exists (
select 'x'
from emp e2
where e1.deptno = e2.deptno
and e2.ename = 'Abel'
)
7 列出每个员工的姓名,工作,部门号,部门名
select ename,job,emp.deptno,dept.dname from emp,dept where emp.deptno=dept.deptno
8 列出emp中工作为'SH_CLERK'的员工的姓名,工作,部门号,部门名
select ename,job,dept.deptno,dname from emp,dept where dept.deptno=emp.deptno and job='SH_CLERK'
9 对于emp中有管理者的员工,列出姓名,管理者姓名(管理者外键为mgr)
select a.ename as 姓名,b.ename as 管理者 from emp a,emp b where a.mgr is not null and a.mgr=b.empno
10 对于dept表中,列出所有部门名,部门号,同时列出各部门工作为'SH_CLERK'的员工名与工作
select dname as 部门名,dept.deptno as 部门号,ename as 员工名,job as 工作 from dept,emp
where dept.deptno = emp.deptno(+) and job = 'SH_CLERK'
11 对于工资高于本部门平均水平的员工,列出部门号,姓名,工资,按部门号排序
select a.deptno as 部门号,a.ename as 姓名,a.sal as 工资 from emp a
where a.sal>(select avg(sal) from emp b where a.deptno=b.deptno) order by a.deptno
(法二)select e.deptno,ename,sal
from emp e,(select deptno,avg(sal) avg_sal from emp group by deptno) b
where e.sal > b.avg_sal and e.deptno = b.deptno