Oracle Analytic Function - Oracle/PLSQL CUME_DIST Function






This Oracle tutorial explains how to use the Oracle/PLSQL CUME_DIST function.

CUME_DIST() returns the position of a value relative to a group. CUME_DIST() is short for cumulative distribution.

The CUME_DIST function can be used as an Aggregate function or as an Analytic function.

CUME_DIST Function Syntax as an Aggregate Function

When used as an Aggregate function, the CUME_DIST function returns the relative position of a row within a group of rows.

The syntax for the CUME_DIST function when used as an Aggregate function is:

CUME_DIST( expression1, ... expression_n ) WITHIN GROUP ( ORDER BY expression1, ... expression_n )

expression1 .. expression_n can be one or more expressions which identify a unique row in the group.

expressions in CUME_DIST must be the same as them in the ORDER BY clause.

The data types must be compatible between the expressions in CUME_DIST and in the ORDER BY clause.





Example as an Aggregate Function

select CUME_DIST(1000, 500) WITHIN GROUP (ORDER BY salary, bonus)
 from employee;

The SQL statement above returns the cumulative distribution of an employee with a salary of $1,000 and a bonus of $500 from within the employees table.

CUME_DIST Function Syntax as an Analytic Function

When used as an analytic function, the CUME_DIST function returns the relative position of a value within a group of values.

The syntax for the CUME_DIST function when used as an Analytic function is:

CUME_DIST() OVER ( [ query_partition_clause] ORDER BY clause )




Example as an Analytic Function


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

SQL> SELECT deptno, SUM(sal),
  2  CUME_DIST() OVER (ORDER BY SUM(sal) DESC) AS cume_dist
  3  FROM emp
  4  GROUP BY deptno
  5  ORDER BY deptno;

    DEPTNO   SUM(SAL)  CUME_DIST
---------- ---------- ----------
        10       5850          1
        20       8275 .666666667
        30       8450 .333333333

SQL>