Return a sum in different rows in mysql

2

I have a table of deposit statements and withdrawals from some clients, as follows:

id_cliente|operação|valor |
----------+--------+------+
51298     |   01   | 50,00|
----------+--------+------+
51298     |   01   | 48,50|
----------+--------+------+
51298     |   02   | 13,67|
----------+--------+------+
51298     |   02   | 18,17|
----------+--------+------+

Operations with values referring to 1 are deposits, with value 2 are withdrawals. How do I perform a query returning the balance amount of the client? An sql that already returns me the difference of values.

    
asked by anonymous 05.05.2016 / 22:50

4 answers

2

Replace column and table names:

select sum(case when operacao='01' then valor else 0 end) deposito,
       sum(case when operacao='02' then valor else 0 end) retirada,
       sum(case when operacao='01' then valor else -1*valor end) saldo
  from tabela
 where id_cliente = 51298
    
06.05.2016 / 03:00
4
The IF function:

MySQL already has its own tool for conditional situations. It is the IF function:

IF( expressão de teste, valor se verdadeiro, valor se falso )


Applying to the question case:

Just a single SUM with IF to get the balance calculated in a single pass through the DB:

SELECT SUM( IF( operacao='01', valor, -valor ) ) AS saldo FROM tabela

Result:

saldo
66.66

See working on SQL Fiddle .


Variants:

If it is to see the balance of a specific customer:

SELECT SUM(IF(operacao='01',valor,-valor )) AS saldo FROM tabela WHERE id_cliente=51298

If it is for multiple clients in the same search:

SELECT SUM( IF( operacao='01', valor, -valor ) ) AS saldo FROM tabela GROUP BY id_cliente
    
06.05.2016 / 04:30
2

You can try this way

select sum(case when operacao=2 then valor*-1 else valor end) 
from tabela 
GROUP by id_cliente
    
06.05.2016 / 03:29
1

Ready:

select 
   (sum(valor) from tabela where operacao = '01') - 
   (sum(valor) from tabela where operacao = '02') saldo

I'm considering that the operation field is a varchar / string. If it is numeric, remove the quotation marks.

    
05.05.2016 / 23:06