Monday, June 1, 2015

Cumulative Sum


To get a cumulative sum, you need to use a window function ‘Rows Between Unbounded Preceding and Current Row’, which tells Oracle that the window it’s summing is between the beginning and the current record.

SELECT deptno, empno, ename, sal
     , SUM(sal) OVER (PARTITION BY deptno
                          ORDER BY empno
                                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
                     ) AS
       cum_sal
  FROM scott.emp
 GROUP BY deptno, empno, ename, sal
 ORDER BY deptno, empno;

No comments:

Post a Comment