AVG function

Avg function operates on a group of rows and return one row of output. Null values are ignored by avg. You can use the DISTINCT keyword to exclude duplicate entries.


SQL> CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
  2                    ENAME VARCHAR2(10),
  3                    JOB VARCHAR2(9),
  4                    SAL NUMBER(7, 2),
  5                    DEPTNO NUMBER(2));
SQL> INSERT INTO EMP VALUES (1, 'SMITH', 'CLERK',     800,    20);
SQL> INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1250,    30);
SQL> INSERT INTO EMP VALUES (3, 'WARD',  'SALESMAN', 1250,    30);
SQL> INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER',  2975,    20);
SQL> INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250,    30);
SQL> INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER',  2850,    30);
SQL> INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER',  2850,    10);
SQL> INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST',  3000,    20);
SQL> INSERT INTO EMP VALUES (9, 'KING',  'PRESIDENT',3000,    10);
SQL> INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500,    30);
SQL> INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK',    1500,    20);
SQL> select avg(sal) from emp;

  AVG(SAL)
----------
2020.45455

SQL>

Using AVG function with group by clause:


SQL> select job, avg(sal) from emp group by job;

JOB         AVG(SAL)
--------- ----------
CLERK           1150
SALESMAN      1312.5
PRESIDENT       3000
MANAGER   2891.66667
ANALYST         3000

SQL>

Doing the calculation inside avg fuction:


SQL> select job, avg(sal+ 1000) from emp group by job;

JOB       AVG(SAL+1000)
--------- -------------
CLERK              2150
SALESMAN         2312.5
PRESIDENT          4000
MANAGER      3891.66667
ANALYST            4000

SQL>

Get the distinct average:


SQL>
SQL> select job, avg(distinct sal) from emp group by job;

JOB       AVG(DISTINCTSAL)
--------- ----------------
ANALYST               3000
CLERK                 1150
MANAGER             2912.5
PRESIDENT             3000
SALESMAN              1375

SQL>
Home »
Oracle »
Aggregate Functions » 

Related: