theDbGuy
theDbGuy

Reputation: 931

sql to generate a column by manipulating previous row and previous column

I have the following in a table

  c1   
  1  
  4  
  3  
  2  
  2  

I need to generate c2 as:

 
  c1 c2  
  1  1
  4  5
  3  8
  2  10
  2  12

The first row of c2 is c1 row value. Now need to add c1's 2nd row and c2's first row for c2's second row.For third row of c2, C2= c1's third + c2's second and so on...

I need this in sql. Is it possible?

I use oracle 11g.

Upvotes: 0

Views: 59

Answers (1)

Captain
Captain

Reputation: 2218

Your algorithm does just simplify to running total:

create table c2 as
select c1
, sum(c1) over (ORDER BY rowid) as c2
from c1;

The order is an issue - we can't ORDER BY NULL. I have used rowid given that your example doesn't order by c1. But if you are doing a running total, you must decided what it is running against!

Upvotes: 1

Related Questions