Oracle第三天

/*
子查询:查询语句中嵌套查询语句;
通常情况下,数据库中不要出现null 最好的做法是加上not null
单行子查询:可以用> >= <> 等作连接
       
多行子查询:
*/
--查询最高工资的员工
select * from emp where sal = (select max(sal) from emp);
--查询出比雇员7654的工资高,同时和7788从事相同工作的员工信息
select * from emp where sal > (select sal from emp where empno = 7654) 
and job = (select job from emp where empno = 7788);
--查询每个部门最低工资的员工信息和他所在的部门信息
select * from emp e,dept d 
here sal in (select min(sal) from emp e group by deptno) 
and e.deptno = d.deptno;

--查询所有经理的编号;
select mgr from emp;
select * from emp where empno in (select mgr from emp);
select distinct mgr from emp where mgr is not null;
--查询不是领导的信息
select * from emp where empno not in (select mgr from emp);--有问题的,因为select mgr from emp;中有个null
--任何子查询中不能去使用not in ,因为当子查询中有null时会出现问题
select * from emp where empno not in (select mgr from emp where mgr is not null);
select * from emp where empno <>all(select mgr from emp);
/*
exists(查询语句):存在的意思
       当作布尔值来处理:
       当查询语句有结果的时候,就是返回true,否则返回的是false
数据量比较大的时候是非常高效的
*/
select * from emp where exists(select * from emp where deptno = 123456);
select * from emp where 3=4;

select * from emp where exists(select * from emp where deptno = 20);
--查询有员工的部门信息;
select * from dept d where exists (select * from emp e where e.deptno = d.deptno);

select * from emp where rownum = 1;
--练习题
--找到员工表中工资最高的前三名
select * from (select * from emp order by sal desc ) where rownum < 4;
--rownum:伪列,系统自动生成的一列,用来表示行号,rownum是oracle中特有的用来表示行号的,默认是从1开始的
--查询rownum大于2的所有记录
select * from emp where rownum >2;--没有记录
--查询rownum 大于等于1的所有记录;
select * from emp where rownum >=1;--全部记录


--找到员工表中薪水大于本部门平均薪水的员工
select * from emp e , (select avg(sal) sal,deptno from emp group by deptno) t 
where e.deptno = t.deptno and e.sal > t.sal;
/*
      关联子查询:
      
      非关联子查询:
*/
select * from emp e 
where sal >(select avg(sal) from emp e2 group by deptno having e.deptno = e2.deptno);
-- 统计每年入职员工的个数
select to_char(e.hiredate,'yyyy') yy,count(*) cc from emp e group by to_char(e.hiredate,'yyyy');
--将yy竖起来
select 
sum(cc) TOTAL,
sum(case yy when '1980' then cc end) "1980",
sum(case yy when '1981' then cc end) "1981",
sum(case yy when '1982' then cc end) "1982",
sum(case yy when '1987' then cc end) "1987"
from 
(select to_char(e.hiredate,'yyyy') yy,count(*) cc from emp e group by to_char(e.hiredate,'yyyy')) e1;

--查询第六条到第十条的记录
select * from (select rownum hang,e.* from emp e) where hang between 6 and 10;
--在oracle中只能通过子查询来做分页

  

猜你喜欢

转载自www.cnblogs.com/pengzhi/p/10591558.html