ORACLE的基础SQL(二)

–多行函数【聚合函数】:作用于多行,返回一个值。
select count(1) from emp;—查询总数量
select sum(sal) from emp;—工资总和
select max(sal) from emp;—最大工资
select min(sal) from emp;—最低工资
select avg(sal) from emp;—平均工资

—分组查询
—查询出每个部门的平均工资
—分组查询中,出现在group by后面的原始列,才能出现在select后面
—没有出现在group by后面的列,想在select后面,必须加上聚合函数。
—聚合函数有一个特性,可以把多行记录变成一个值。
select e.deptno, avg(e.sal)–, e.ename
from emp e
group by e.deptno;
—查询出平均工资高于2000的部门信息
select e.deptno, avg(e.sal) asal
from emp e
group by e.deptno
having avg(e.sal)>2000;
—所有条件都不能使用别名来判断。
–比如下面的条件语句也不能使用别名当条件
select ename, sal s from emp where sal>1500;

—查询出每个部门工资高于800的员工的平均工资
select e.deptno, avg(e.sal) asal
from emp e
where e.sal>800
group by e.deptno;
—-where是过滤分组前的数据,having是过滤分组后的数据。
—表现形式:where必须在group by之前,having是在group by之后。
—查询出每个部门工资高于800的员工的平均工资
—然后再查询出平均工资高于2000的部门
select e.deptno, avg(e.sal) asal
from emp e
where e.sal>800
group by e.deptno
having avg(e.sal)>2000;

—多表查询中的一些概念
—笛卡尔积
select *
from emp e, dept d;
—等值连接
select *
from emp e, dept d
where e.deptno=d.deptno;
—内连接
select *
from emp e inner join dept d
on e.deptno = d.deptno;
—查询出所有部门,以及部门下的员工信息。【外连接】
select *
from emp e right join dept d
on e.deptno=d.deptno;
—查询所有员工信息,以及员工所属部门
select *
from emp e left join dept d
on e.deptno=d.deptno;
—oracle中专用外连接
select *
from emp e, dept d
where e.deptno(+) = d.deptno;

select * from emp;
—查询出员工姓名,员工领导姓名
—自连接:自连接其实就是站在不同的角度把一张表看成多张表。
select e1.ename, e2.ename
from emp e1, emp e2
where e1.mgr = e2.empno;

——查询出员工姓名,员工部门名称,员工领导姓名,员工领导部门名称
select e1.ename, d1.dname, e2.ename, d2.dname
from emp e1, emp e2, dept d1, dept d2
where e1.mgr = e2.empno
and e1.deptno=d1.deptno
and e2.deptno=d2.deptno;

—子查询
—子查询返回一个值
—查询出工资和SCOTT一样的员工信息
select * from emp where sal in
(select sal from emp where ename = ‘SCOTT’)
—子查询返回一个集合
—查询出工资和10号部门任意员工一样的员工信息
select * from emp where sal in
(select sal from emp where deptno = 10);
—子查询返回一张表
—查询出每个部门最低工资,和最低工资员工姓名,和该员工所在部门名称
—1,先查询出每个部门最低工资
select deptno, min(sal) msal
from emp
group by deptno;
—2,三表联查,得到最终结果。
select t.deptno, t.msal, e.ename, d.dname
from (select deptno, min(sal) msal
from emp
group by deptno) t, emp e, dept d
where t.deptno = e.deptno
and t.msal = e.sal
and e.deptno = d.deptno;

—-oracle中的分页
—rownum行号:当我们做select操作的时候,
–每查询出一行记录,就会在该行上加上一个行号,
–行号从1开始,依次递增,不能跳着走。

—-排序操作会影响rownum的顺序
select rownum, e.* from emp e order by e.sal desc
—-如果涉及到排序,但是还要使用rownum的话,我们可以再次嵌套查询。
select rownum, t.* from(
select rownum, e.* from emp e order by e.sal desc) t;

—-emp表工资倒叙排列后,每页五条记录,查询第二页。
—-rownum行号不能写上大于一个正数。
select * from(
select rownum rn, tt.* from(
select * from emp order by sal desc
) tt where rownum<11
) where rn>5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值