Sum between MySQL rows

3

I'm having trouble performing an operation using MySQL, I do not even know if it's possible to do what I want.

I have a table_control table, in this table I have all operations that are performed with products.

In stock_control I have a column called typeMoviment which is 1 for input and 0 for output; What I want to do is this:

select * sum(quantidade) from controle_de_estoque where tipoMovimentacao = 0 MENOS select * sum(quantidade) from controle_de_estoque where tipoMovimentacao = 0

That is, I want to subtract one from the other but everything I try from the error.

Does anyone know what I can do?

Thank you.

    
asked by anonymous 25.10.2017 / 15:56

3 answers

5

With a single query you can get the balance if you condition the sum for each type of movement.

Total entries - Total outputs

See:

select sum(case when tipoMovimentacao = 1 then quantidade else 0 end) 
       - sum(case when tipoMovimentacao = 0 then quantidade else 0 end)
from controle_de_estoque 

Performing a single query to the bank will give you a better performance. The cost is almost half that of two select sum() .

    
25.10.2017 / 16:31
1
 select   
 (select * sum(quantidade) from controle_de_estoque where tipoMovimentacao = 0)  
 -  
 (select * sum(quantidade) from controle_de_estoque where tipoMovimentacao = 1) as ESTOQUEATUAL   
from dual 

This is how it works.

    
25.10.2017 / 16:00
1

You can use a case, if your intent and subtract the amount between types, there's no way you can do for all the fields like you used in your script

  

select * sum (

select * ,
    case whan tipoMovimentacao = 0 then sum(quantidade) end
    -
    case when tipoMovimentacao = 1 then sum(quantidade) end
from controle_de_estoque

or a sub select.

 select   
 (select sum(quantidade) from Products where tipoMovimentacao = 0)  
 -  
 (select sum(quantidade) from controle_de_estoque where tipoMovimentacao = 1)
    
25.10.2017 / 16:25