# SQL子查询

1. 包含在select子句中的子查询：

SQL> select dname,(select max(sal) from emp where deptno=dept.deptno) max_sal
2 from dept
3 /

DNAME MAX_SAL
-------------- ----------
ACCOUNTING 5000
RESEARCH 3000
SALES 2850
OPERATIONS

SQL> select deptno,max(sal) from emp
2 group by deptno
3 /

DEPTNO MAX(SAL)
---------- ----------
30 2850
20 3000
10 5000

SQL> select d.dname, max(e.sal)
2 from emp e, dept d
3 where e.deptno=d.deptno
4 group by dname
5 /

DNAME MAX(E.SAL)
-------------- ----------
ACCOUNTING 5000
RESEARCH 3000
SALES 2850

SQL> select ename,(select dname from dept where deptno=emp.deptno) dname
2 from emp
3 /

ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH

SQL> select e.ename,d.dname
2 from emp e, dept d
3 where e.deptno=d.deptno
4 /

ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH

SQL> select ename, sal, (select avg(sal) from emp) avgsal
2 from emp
3 /

SQL> select ename, sal,
2 (select avg(sal) from emp where emp.deptno=emp1.deptno) avgsal
3 from emp emp1
4 /

2. 包含在where子句中的子查询：

SQL> select dname
2 from dept
3 where deptno=(select deptno from emp)
4 /
where deptno=(select deptno from emp)
*
ERROR at line 3:
ORA-01427: single-row subquery returns more than one ro

SQL> select dname
2 from dept
3 where deptno in (select deptno from emp)
4 /

DNAME
--------------
RESEARCH
SALES
ACCOUNTING

SQL> select ename
2 from emp
3 where sal>all(select sal from emp where deptno=30)
4 /

ENAME
----------
JONES
SCOTT
KING
FORD

SQL> select dname
2 from dept
3 where deptno in
4 (
5 select deptno from emp
6 group by deptno
7 having count(empno)>3
8 )
9 /

DNAME
--------------
SALES
RESEARCH

3. 包含在from子句中的子查询：

SQL> select to_char(hiredate,'yyyy') hireYear,count(empno)
2 from emp
3 group by hireYear
4 /
group by hireYear
*
ERROR at line 3:
ORA-00904: "HIREYEAR": invalid identifier

SQL> select hireYear,count(empno)
2 from (select to_char(hiredate,'yyyy') hireYear, empno from emp)
3 group by hireYear
4 /

HIRE COUNT(EMPNO)
---- ------------
1987 2
1980 1
1982 1
1981 10

SQL> select hireYear,count(empno)
2 from (select to_char(hiredate,'yyyy') hireYear, empno from emp) d
3 group by hireYear
4 /

HIRE COUNT(EMPNO)
---- ------------
1987 2
1980 1
1982 1
1981 10

SQL> select hireYear,count(empno)
2 from
3 (select to_char(hiredate,'yyyy') hireYear,empno
4 from (select * from emp) d1
5 ) d2
6 group by hireYear
7 /

HIRE COUNT(EMPNO)
---- ------------
1987 2
1980 1
1982 1
1981 10

• 博文量
279
• 访问量
932078