How to sum based on field value (mysql)

I got this table named tb_stock

 ID AMOUNT FLAG LAST_AMOUNT 1 5 N 0 2 0 Y 8 3 0 Y 7 4 6 N 0 

Now I want to sum the value based on the FLAG value. For example, if the FLAG values ​​are N, they will be summed from the AMOUNT field, and if the FLAG value is Y, it will be summed from the LAST_AMOUNT field.

Thus, the total amount will be 26 (5 + 8 + 7 + 6).

Can this be done simply using mysql or will it also include php?

Thanks.

+4
source share
2 answers
 SELECT SUM(CASE WHEN FLAG = 'Y' THEN LAST_AMOUNT ELSE AMOUNT END) AS TOTAL FROM tb_stock 
+5
source

this is an example using an IF

 SELECT SUM(IF(`flag`='y', last_amount, amount)) FROM example_table 
0
source

All Articles