Link to home
Start Free TrialLog in
Avatar of subratoc
subratoc

asked on

cumulative figures in oracle sql

Is it possible to calculate cumulatively in oracle, i.e. using the results of the last row for calculating the values in the current row?
For example I want my query to return the following:
Month      col1      _      col2      _      col3
jan      1      _      100      _      100 * 1
feb      2      _      200      _      100 * 2 + 200
mar      3      _      300      _      400 * 3 + 300
apr      4      _      400      _      1500 * 4 + 400
may      5      _      500      _      6400 * 5 + 500

In col3 above, for feb I want to use the result returned for jan ((100 * 1)*2+200),
for mar I am using the result returned for feb((100 * 2 + 200) * 3 + 300) and so on.

i.e. I want to use the previous value of column3 to derive the current value of column3.
Like using the LAG function but on the analytically derived column itself.

Thanks in advance.

Avatar of Ivo Stoykov
Ivo Stoykov
Flag of Bulgaria image

yes use LAG function
LAG (<sql_expr>, <offset>, <default>) OVER (<analytic_clause>)

HTH

Ivo Stoykov

PS: here there is some help about
SELECT deptno, empno, sal,
LEAD(sal, 1, 0) OVER (PARTITION BY dept ORDER BY sal DESC NULLS LAST) NEXT_LOWER_SAL,
LAG(sal, 1, 0) OVER (PARTITION BY dept ORDER BY sal DESC NULLS LAST) PREV_HIGHER_SAL
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, sal DESC;

 DEPTNO  EMPNO   SAL NEXT_LOWER_SAL PREV_HIGHER_SAL
------- ------ ----- -------------- ---------------
     10   7839  5000           2450               0
     10   7782  2450           1300            5000
     10   7934  1300              0            2450
     20   7788  3000           3000               0
     20   7902  3000           2975            3000
     20   7566  2975           1100            3000
     20   7876  1100            800            2975
     20   7369   800              0            1100

8 rows selected.

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Naveen Kumar
Naveen Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think in this case function is better and you can easily modify it in future for any changes/modifications though it may be possible to directly do it with a SQL query but the complexity of the SQL query will end in difficult situation to modify for future needs.