Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL adding value from previous row

I have a table with a single column. The column is like this:

1
2
3
4
5
...

I want to create a query that will display another column that will have the previous value added to it. So:

1 1 ( 0 + 1 )
2 3 ( 1 + 2 )
3 5 ( 2 + 3 )
4 7 ( 3 + 4 )
5 9 ( 4 + 5 )
9 14 (5 + 9)
45 54 ( 9 + 45)

How would I construct a query to accomplish that?

Essentially, I just want the difference between ROW[X], and ROW[X-1].

like image 259
nick Avatar asked Dec 06 '22 11:12

nick


1 Answers

SELECT  a.val, (@runtot :=  a.val  + @runtot) AS rt, ( @runtot := a.val ) ne
FROM    Table1 a,(SELECT @runtot:=0) c

This seems to be working. I tried reinit the variable at each stage. Try it out.

SQLFiddle Demo

like image 159
jaipster Avatar answered Dec 10 '22 10:12

jaipster