oracle多表查询和子查询练习

时间:2023-02-23 14:52:33

--1.列出至少有三个员工的所有部门和部门信息。
SELECT D.DEPTNO, D.DNAME, D.LOC, T.COUNTS
   FROM DEPT D, (SELECT DEPTNO, COUNT(*) COUNTS FROM EMP GROUP BY DEPTNO) T
  WHERE D.DEPTNO = T.DEPTNO
    AND T.COUNTS >= 3;
 
--2.列出受雇日期早于直接上级的所有员工的编号,姓名,部门名称
SELECT E.EMPNO, E.ENAME, D.DNAME
   FROM EMP E, EMP M, DEPT D
  WHERE E.MGR = M.EMPNO
    AND E.HIREDATE < M.HIREDATE
    AND E.DEPTNO = D.DEPTNO;

  
--3.列出职位为“CLERK”的员工姓名和其所在部门名称,部门人数:
SELECT e.ename,d.dname,t.counts
FROM emp e, dept d,
      (SELECT deptno de, COUNT(*) counts FROM emp GROUP BY deptno )t
WHERE e.deptno = d.deptno AND e.deptno = t.de AND e.job = 'CLERK';

--4.列出和“SCOTT”从事相同工作的所有员工及部门名称:
SELECT E.*, D.DNAME
   FROM EMP E, DEPT D
  WHERE E.DEPTNO = D.DEPTNO
    AND E.JOB = (SELECT JOB FROM EMP WHERE ENAME = 'SCOTT');

--5.列出每个部门工作的员工数量、平均工资和平均服务期限(单位为年)
SELECT DEPTNO "部门编号",
        COUNT(EMPNO) "人数",
        ROUND(AVG(SAL)) "平均薪资",
        ROUND(AVG(MONTHS_BETWEEN(SYSDATE, HIREDATE))/12) "服务年限"
   FROM EMP
  GROUP BY DEPTNO;

--6、列出各个部门的MANAGER 的最低薪金:
SELECT deptno, MIN(sal) FROM emp WHERE job = 'MANAGER' GROUP BY deptno;

--7、给任职日期超过10年的人加薪10%;
SELECT E.*, E.SAL * 1.1
   FROM EMP E
  WHERE (MONTHS_BETWEEN(SYSDATE, HIREDATE)) / 12 > 10;