MySQL adds the value from the previous row

I have a single column table. The column is as follows:

1 2 3 4 5 ... 

I want to create a query that displays 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 do I build a query to accomplish this?

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

+4
source share
2 answers
 SELECT a.val, (@runtot := a.val + @runtot) AS rt, ( @runtot := a.val ) ne FROM Table1 a,(SELECT @runtot:=0) c 

It seems to work. I tried to reset the variable at every step. Give it a try.

SQLFiddle Demo

+12
source

TRY

 SELECT a.int, (@runtot := a.int + a.int - 1) AS rt FROM test a,(SELECT @runtot:=0) c 

ie

 1 1 ( 0 + 1 ) 2 3 ( 1 + 2 ) 3 5 ( 2 + 3 ) 4 7 ( 3 + 4 ) 5 9 ( 4 + 5 ) 

this will result in the output you showed.

-1
source

Source: https://habr.com/ru/post/1440202/


All Articles