Sum if in Mysql Workbench

Asked

Viewed 210 times

3

I have a database in Mysql.

No_Pedido|Valor|Cortesia
123|1000|Sim
123|500|Nao
124|200|Nao
124|500|Nao 

I need to make a select that returns the sum of the value per request that is not courtesy,

would be a sumif..

Select needs to stay that way:

No_Pedido|Valor|Cortesia
123|500|Nao
124|700|Nao 

To using the following query:

select sum(case when cortesia = 'Sim' then valor else 0 end) from tabela;

And the result is not as expected...

Any suggestions?

  • What result are you having and why it is not as expected?

2 answers

3


For the expected result you should group by order number and courtesy and not try to separate into different columns.

select No_Pedido,
       sum(valor),
       Cortesia
  from tabela
  group by No_Pedido,
           Cortesia;

1

You can bring only the records that interest you and filter the others using the clause WHERE. Here’s an example of what it would look like:

SELECT No_Pedido, SUM(Valor)
FROM tabela
WHERE cortesia = "nao"

Browser other questions tagged

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