Add two columns and subtract with condition

Asked

Viewed 73 times

0

I am trying to sum two columns after subtracting the following way in sql:

SELECT sum(valor) WHERE lancamentotipo = "R" - sum(valor) WHERE lancamentotipo = "D" from lancamentos

From the above by adding a "WHERE" clause I get error however if I do it as follows it works:

SELECT sum(valor) - sum(valor2) from lancamentos

How do I insert a "WHERE" clause correctly in the above case, because I’m sure I’m missing something simple, because I want to add and subtract values from the same table with a certain condition.

1 answer

0

An alternative is:

SELECT SUM(CASE WHEN lancamentotipo = "R" THEN valor WHEN lancamentotipo = "D" THEN -valor ELSE 0 END) AS resultado FROM lancamentos;

If "R" and "D" are the only possible values lancamentotipo can assume then just replace the second clause WNEN by a ELSE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.