1

I have table named ct_rt and there is one field ct. The data in the filed is following :

100
450
-20
500
300
-50

Now i want to get the following result :

100
550
530
1030
1330
1280

which is the addition of each row with its succeeding row. So how can I get the desired output ? I am using Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production. Please help me.

Thank you. :)

1
  • Have you tried to write the query yet? Please post your query if yes. Dec 4, 2014 at 8:00

3 Answers 3

4

This can be done using a window function with a "cumulative sum":

select ct,
       sum(ct) over (order by some_column) as the_sum
from ct_rt
order by some_column;

You have to supply a column to sort the result. Rows in a relation database are not sorted and come in essentially a random order unless you specify an order by. The cumulative sum has the same "restriction" and therefor you have to supply an order by in the definition of the window function.

A good candidate for sorting this result is a timestamp column that defines when the row has been inserted (or updated). A unique, increasing id column is also a good candidate.

3
0

Solution using a correlated subquery (you need an id field though)

SELECT (
    SELECT sum(ct) 
    FROM ct_rt AS sub
    WHERE sub.id <= qry.id
)
FROM ct_rt AS qry
ORDER BY qry.id

Edit: This is an alternative solution. The solution of a_horse_with_no_name will most propably outperform this.

1
  • 1
    This is not necessary in Oracle. The solution with the window function will perform much better. Dec 4, 2014 at 8:46
-2

Check this one it may help you

select numbers,SUM(numbers) over(order by rowid) nxtx
from txd;
10
  • 1
    This doesn't improve on the good answer by a_horse_with_no_name, but is rather bad, because order by rowid is arbitrary and random
    – Falco
    Dec 4, 2014 at 10:33
  • 1
    but its not necessary,if its in any order then it may result to wrong answer even in the the case of some column id and if one wants the result in the same manner the data is entered than its useful... Dec 4, 2014 at 10:39
  • and even i didn't saw the above answer when i posted it as i didn't refreshed my page as it was open from long time .... that answer is correct too but could lead to wrong answer when it comes to bulk data and one requires the result in the way the data is inserted . Dec 4, 2014 at 10:45
  • even one can use rowid with some column id if required, to get appropriate result in the manner of data insertion – Dec 4, 2014 at 11:53
  • 1
    Sorting by rowid does not sort "in the way the data is inserted". Dec 8, 2014 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.