CASE inside SUM to normalize cash direction
SELECT
stock_name,
SUM(
CASE
WHEN operation = 'Buy' THEN -price
ELSE price
END
) AS capital_gain_loss
FROM stocks
GROUP BY stock_nameThis is the cleanest solution. It translates each row into signed cash flow first, then adds the flows per stock to get the net gain or loss.