计算同一列中两个值的差异

问题描述 投票:0回答:2

当我将记录与相同的CATEGORY值组合时,我想找到差异(利润和损失)(例如,A将被组合并且C将被组合)。

sql ms-access
2个回答
2
投票

我想你想要条件聚合:

select category,
       sum(iif(side = "BUY", - quantity * price, quantity * price)) as net
from t
where side in ("BUY", "SELL")  -- may not be necessary
group by category;

1
投票
Select category, buy.amt-sell.amt ProfitorLoss
from
(SELECT sum(price*quantity) amt, Category
  FROM yourtable
 WHERE side = 'BUY'
GROUP BY Category) buy,
(SELECT sum(price*quantity) amt, Category
  FROM yourtable
 WHERE side = 'SELL'
GROUP BY Category) sell
where buy.category = sell.category
© www.soinside.com 2019 - 2024. All rights reserved.