'Sum if' in MySql workbench

3

I have a MySql database.

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 polite,

would be sumif ..

Select needs to look like this:

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?

    
asked by anonymous 08.11.2016 / 20:04

2 answers

3

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

select No_Pedido,
       sum(valor),
       Cortesia
  from tabela
  group by No_Pedido,
           Cortesia;
    
08.11.2016 / 20:12
1

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

SELECT No_Pedido, SUM(Valor)
FROM tabela
WHERE cortesia = "nao"
    
10.11.2016 / 12:35