当我将记录与相同的CATEGORY
值组合时,我想找到差异(利润和损失)(例如,A将被组合并且C将被组合)。
我想你想要条件聚合:
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;
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