mysql中sum (if)_mysql 中sum (if())
生活随笔
收集整理的這篇文章主要介紹了
mysql中sum (if)_mysql 中sum (if())
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
先來一個(gè)簡單的sum
select sum(qty) as total_qty from inventory_product group by product_id
這樣就會(huì)統(tǒng)計(jì)出所有product的qty.
但是很不幸,我們的系統(tǒng)里面居然有qty為負(fù)值。而我只想統(tǒng)計(jì)那些正值的qty,加上if function就可以了。 SQL為:
select sum(if(qty > 0, qty, 0)) as total_qty?? from inventory_product group by product_id
意思是如果qty > 0, 將qty的值累加到total_qty, 否則將0累加到total_qty.
再加強(qiáng)一點(diǎn):
select sum( if( qty > 0, qty, 0)) as total_qty?? , sum( if( qty < 0, 1, 0 )) as negative_qty_count from inventory_product? group by product_id
總結(jié)
以上是生活随笔為你收集整理的mysql中sum (if)_mysql 中sum (if())的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php mysql 框架_Medoo 轻
- 下一篇: mysql为什么要转es_MySQL用得