Error using "greater than" in select command with case

Asked

Viewed 372 times

2

I am trying to execute the following select command:

SELECT 
estoque.id,
produto.id,
produto.descricao PRODUTO,
case saida.quant when > 0 then (estoque.quant + sum(saida.quant)) else estoque.quant end ESTOQUE
FROM estoque, saida, produto
join produto on estoque.idProduto = produto.id
join saida on estoque.id = saida.idEstoque
where estoque.idUnidade = '0'
group by estoque.id

I get an error in the case line where you have the symbol >. He says he’s not allowed to be there.

My intention is that, should saida.quant is greater than zero, it sums up with estoque.quant, when less than zero, list only estoque.quant

1 answer

3


According to the documentation, the syntax of your query is incorrect. It should be something like this:

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

What you can do, is reverse the order of the comparison and so will not need more >. See below:

SELECT 
estoque.id,
produto.id,
produto.descricao PRODUTO,
case saida.quant when 0 then estoque.quant else (estoque.quant + sum(saida.quant)) end ESTOQUE
FROM estoque, saida, produto
join produto on estoque.idProduto = produto.id
join saida on estoque.id = saida.idEstoque
where estoque.idUnidade = '0'
group by estoque.id

If you want to consider negative values, it can be done this way according to the same logic but with the correct syntax. See:

case when saida.quant>0 then estoque.quant else (estoque.quant + sum(saida.quant)) end...
  • How to know if it is greater than zero or less?

  • 1

    @Italorodrigo is possible to be smaller?! Logic is that if it is 0 do something else, consider all values. I will edit to improve this.

Browser other questions tagged

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