#查询总结六
#在from子句中使用子查询,如何显示高于自己部门平均工资的员工的信息
- 查询出各个部门的平均工资和部门号
select deptno,avg(sal) from emp group by deptno;
- 把上面的查询看做一张子表
select a2.ename,a2.sal,a2.deptno,a1.mysal from emp a2,(select deptno,avg(sal) mysal from emp group by deptno) a1 where a2.deptno=a1.deptno and a2.sal >a1.mysal
总结:当在from使用子查询时,这样子查询会被当做一个视图来对待,因此叫内嵌视图,当在from子句中使用子查询时,必须给子查询指定别名。
#分页查询
按雇员的id 号升序取出
//Oracle分页一共有三种方式
- rownum 分页
select a1.*,rownum rn from (select * from emp) a1;
- 显示rownum[oracle分配的]
select a1.*,rownum rn from (select * from emp) a1 where rownum <=10;
- select * from (select a1.*,rownum rn from (select * from emp) a1 where rownum <=10) where rn>=5;
指定查询列,只需修改最里层的子查询。
select * from (select a1.*,rownum rn from (select ename,sal from emp) a1 where rownum <=10) where rn>=5;
如何排序
select * from (select a1.*,rownum rn from (select ename,sal from emp order by sal) a1 where rownum <=10) where rn>=5;
用查询结果创建新表
create table mytable (id,name,sal,job,deptno) as select empno,ename,sal,job,deptno from emp
合并查询
#使用集合操作符,union,union all,intersect,minus
#union
两个结果集的并集,去掉重复行
select ename,sal,job from emp where sal>2500 union
select ename,sal,job from emp where job=’MANAGER’;
#union all ,不去重复
select ename,sal,job from emp where sal>2500 union all
select ename,sal,job from emp where job=’MANAGER’;
#intersect 交集
#minus 差集