Neeko
Neeko

Reputation: 1149

Get previous row's value on a MySQL view

Assuming I have something like this :

MySQL table

Date        |   Val   
2013/11/22  |   2     
2013/11/23  |   4     
2013/11/25  |   12    
2013/11/30  |   28    
2013/12/02  |   2     

I need a query to get on an other column the sum of the "current" row's value plus the previous row's value. With the example, the result would be something like this :

Date        |   Value   |  Total
2013/11/22  |   2       |  2
2013/11/23  |   4       |  6          <--- Because 4+2 = 6
2013/11/25  |   12      |  16
2013/11/30  |   28      |  40
2013/12/02  |   2       |  30

The problem is that I can't use variables because I'm on a view.

How can I do this ?

Any help is appreciated.

Upvotes: 2

Views: 1257

Answers (1)

fancyPants
fancyPants

Reputation: 51868

SELECT
t.Date,
t.Val,
COALESCE((SELECT Val FROM Table1 sq WHERE sq.Date < t.Date ORDER BY sq.Date DESC LIMIT 1), 0) + t.Val AS whatever
FROM
Table1 t
ORDER BY t.Date

Upvotes: 3

Related Questions