Subquery 4 (use subquery in select clause), select clause
Example 1,Query the number, name, location, department count, and average salary of each department.
SELECT d.deptno,d.dname,d.loc, (SELECT COUNT(empno) FROM emp WHERE emp.deptno=d.deptno GROUP BY deptno) con, (SELECT AVG(sal) FROM emp WHERE emp.deptno=d.deptno GROUP BY deptno) avgsalFROM dept d
WITH clause
Example 2,Use the with clause to define data in the emp table as a temporary table
WITH e AS(SELECT * FROM emp)SELECT * FROM e;
Example 3,Query the number, name, location, average department salary, and number of people of each department
-- Query the ID, name, location, average department salary, number of people WITH e AS (SELECT deptno dno, ROUND (AVG (sal), 2) avgsal, COUNT (empno) con FROM emp group by deptno) SELECT d. deptno, d. dname, d. loc, e. avgsal, e. conFROM dept d, eWHERE d. deptno = e. dno (+ );
Example 4,Query the employee ID, name, position, employment date, salary, department ID, and department name of each department. The result is sorted by department ID.
WITH e AS( SELECT deptno dno,MAX(sal) maxsal FROM emp GROUP BY deptno)SELECT em.ename,em.job,em.hiredate,em.sal,d.deptno,d.dnameFROM emp em,dept d,eWHERE em.deptno=e.dno AND em.sal=e.maxsal AND d.deptno=e.dno ORDER BY em.deptno;