select column, from table_name [where condition] [group by group_by_condition] [having group_condition] [order by column]; -- 平均工资 select deptno,avg(sal) from emp group by deptno;
错误写法:
1 2
select a,b,avg(x) from emp group by a; -- b必须出现在group by 后面。
-- 管理者和下属可以理解为树结构关系,emp.mgr指向管理者emp.empno select level, empno, ename, sal, mgr from emp connect by prior empno=mgr start with mgr is null order by 1; -- level是一个伪劣,相当于树结构的层次,越高层越小,从1开始,order by 1代表根据level排序
-- 正确的写法 select rownum, empno, ename, sal from(select * from emp order by sal desc)where rownum<=3;
1 2 3 4
--一般先执行子查询,再执行主查询;但是相关子查询例外,例如下面的相关子查询(子查询要依赖于父查询)。 -- 找到员工表中薪水大于本部门平均薪水的员工 select empno,ename,sal, (select avg(e2.sal) from emp e where e2.dept=e1.dept) avgsal from emp e where e.sal > (select avg(e2.sal) from emp e where e2.dept=e1.dept); 以上就是相关子查询实例,
子查询的类型
子查询分单行子查询和多行子查询。 多行操作符:in,any,all
1 2 3 4 5 6 7 8 9 10 11 12 13
-- 查询工资大于部门号30的任意一个员工工资的员工 select * from emp e where e.sal > any (select sal from emp where deptno=30); -- 或者使用min函数 select * from emp e where e.sal > (select min(sal) from emp where deptno=30); 查询工资大于部门号30所有人工资的员工 select * from emp e where e.sal > any (select sal from emp where deptno=30); -- 同样可以用max函数 -- 查询不是老板的员工 -- 下面是错误写法: select * from emp where empno not in (select mgr from emp);--空结果 --原因:a not in (10,20,null) == a!=10 and a!=20 and a!=null 最后一个条件永远不假 -- 正确写法 select * from emp where empno not in (select mgr from emp where mgr is not null);
综合示例
1 2 3 4 5 6
-- 分页案例 查询排序后的5到8条记录 select * from (select rownum r,* from (select * from emp order by desc) e1 where rownum <= 8) e2 where e2.r > 5;
-- 按照入职年份查询员工的人数, 例如1981 select count(*) total, sum(decode(to_char(hiredate, 'YYYY'), '1981', 1, 0)) '1981' from emp; select (select count(*) from emp) total, (select count(*) from emp where ...) '1981' fro dual;