MySQL adding value from previous row

nick picture nick · Oct 17, 2012 · Viewed 7.8k times · Source

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].

Answer

jaipster picture jaipster · Oct 17, 2012
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