简体   繁体   中英

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

Right now i want to sum the value based on the FLAG value. For example if the FLAG values is N, it will sum from the AMOUNT field and if the FLAG value is Y, it will sum from the LAST_AMOUNT field.

So the total amount would be 26 (5 + 8 + 7 + 6).

Is this can be achieve with just use mysql or it will involve php as well?

Thanks.

SELECT SUM(CASE WHEN FLAG = 'Y' THEN LAST_AMOUNT ELSE AMOUNT END) AS TOTAL
FROM tb_stock

this is an example using IF statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM