oracle组函数、多表查询、

平均工资:

SQL> select sum(sal)/count(*) 一, avg(sal) 二 from emp;

        一         二
---------- ----------
2073.21429 2073.21429

空值  组函数会自动滤空

SQL> select  comm from emp;

      COMM
----------

       300
       500

      1400




         0


      COMM
----------




已选择14行。

作为参照:

SQL> select count(*),count(comm) from emp;

  COUNT(*) COUNT(COMM)
---------- -----------
        14           4

可以在组函数中嵌套滤空函数,来屏蔽组函数的滤空功能:

SQL> select count(*),count(nvl(comm,0)) from emp;

  COUNT(*) COUNT(NVL(COMM,0))
---------- ------------------
        14                 14

查询平均工资大于2000的部门:

SQL> ed
已写入 file afiedt.buf

  1  select deptno,avg(sal)
  2      from emp
  3      group by deptno
  4*    having avg(sal)>2000
SQL> /

    DEPTNO   AVG(SAL)
---------- ----------
        20       2175
        10 2916.66667

求10号部门的平均工资:

SQL> ed
已写入 file afiedt.buf

  1  select deptno,avg(sal)
  2      from emp
  3      group by deptno
  4*     having deptno=10
SQL> /

    DEPTNO   AVG(SAL)
---------- ----------
        10 2916.66667

此时改用 where:

SQL> ed
已写入 file afiedt.buf

  1  select deptno,avg(sal)
  2      from emp
  3      group by deptno
  4*     where deptno=10
SQL> /
    where deptno=10
    *4 行出现错误:
ORA-00933: SQL 命令未正确结束

内连接:

语法一:

select *  from 表1 [inner] join 表2 on 表1.字段1=表2.字段1;

语法二:

select *   from 表1,表2  where 表1.字段1=表2.字段1;

外连接:
1、左连接:

select * from 表1 left outer join 表2 on 表1.字段1=表2.字段1;
select * from 表1 left outer join 表2 where 表1.字段1=表2.字段1;

2、右连接:

select *  from 表1 right outer join 表2  on 表1.字段1=表2.字段1;
select *  from 表1 left outer join 表2  where 表1.字段1(+)=表2.字段1;

3、全外连接:

select *   from 表1 full outer join 表2  on 表1.字段1=表2.字段1;

自连接:
举个例子:

自连接(selfjoin)是SQL语句中经常要用的连接方式,使用自连接可以将自身表的一个镜像当作另一个表来对待,从而能够得到一些特殊的数据。
示例:
  在oracle的scott的schema中有一个表是emp。在emp中的每一个员工都有自己的mgr(经理),并且每一个经理自身也是公司的员工,自身也有自己的经理。
但现在我们只有一张emp表。所以我们可以采用自连接。自连接的本意就是将一张表看成多张表来做连接。我们可以这样来写SQL语句:

SQL> select a.ename as 员工,b.ename as 上级 from emp a,emp b where a.mgr=b.empno;

员工                 上级
-------------------- --------------------
FORD                 JONES
SCOTT                JONES
JAMES                BLAKE
TURNER               BLAKE
MARTIN               BLAKE
WARD                 BLAKE
ALLEN                BLAKE
MILLER               CLARK
ADAMS                SCOTT
CLARK                KING
BLAKE                KING

员工                 上级
-------------------- --------------------
JONES                KING
SMITH                FORD

已选择13行。

交叉连接: 表与表之间做笛卡尔积查询!:

select * from 表1 cross join 表2;
        
select * from 表1, 表2;

猜你喜欢

转载自www.cnblogs.com/scw123/p/9614831.html