How to calculate the difference between values that are in the same column?

5

I wonder if there is any way to calculate the difference between values that are in the same column. For example: I have a table with 2 fields: date and balance. I need to add a new field containing the balance difference from one date to another.

Dia        Saldo      Variação
------------------------------
01/12 ---  10 ------- 0  
02/12 ---  30 ------- 20  
03/12 ---  70 ------- 40  
04/12 ---  80 ------- 10  
    
asked by anonymous 09.12.2014 / 18:46

2 answers

4

You can do this as follows:

SELECT 
    m.id,
    m.data,
    m.saldo,
    IFNULL(saldo - (SELECT mt.saldo FROM movimento mt WHERE mt.id < m.id ORDER BY mt.id DESC LIMIT 0,1), 0) AS variacao
FROM movimento m

Take a look at sqlfiddle.com

    
09.12.2014 / 19:32
-1

I know two options, you bring this in a query as in Calculate between fields

SELECT ValorBoleto + TotalJuros AS Preco FROM fotoprodutos

or this SQL Formula

SELECT name, black, yellow, white, qty_job (SUM(black) + SUM(yellow) + SUM(white)*0.4) / qty_job AS total FROM counter GROUP BY name;

Another option is for you to do this via the programming language. When you save, you calculate the field before filling it. But in this case, we would need to know the programming language to help you better.

    
09.12.2014 / 19:02