[英]How query two different Sum from the same table for the same column but with different condition?
[英]mysql query from 1 table that return sum of same column which different condition
我有1個交易記錄表,其中包含列數。 桌子看起來像這樣
item quantity
1 10
1 15
1 -10
2 10
3 5
3 -10
數量為+表示購買,而-表示出售。 我想在1個查詢中按item_id計算購買和出售組的總數量總和。
結果應該是這樣的:
item buy sell
1 25 -10
2 10 0
3 5 10
我試圖做這樣的查詢:
SELECT item, SUM(quantity>0) as buy, SUM(quantity<0) as sell FROM table GROUP BY item
但是它返回行數而不是數量的總和。 任何想法如何做到這一點1查詢? 非常感謝!
PS:我知道我必須合並IF NULL才能使項目2返回0而不是null。
您可以使用case
:
select item, sum(case when quantity>0 then quantity else 0 end) as buy,
sum(case when quantity<0 then quantity else 0 end) as sell
from x
您可以像這樣的用戶
SELECT item,SUM(CASE WHEN quantity > 0 THEN quantity END) AS buy
,SUM(CASE WHEN quantity < 0 THEN quantity END) AS Sell
FROM `test`
GROUP BY item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.