MySQL: SUM + CASE + GROUP BY
SELECT stock_name, SUM(\n    CASE\n    WHEN operation = "Buy" THEN -price\n    ELSE price\n    END) AS capital_gain_loss\nFROM Stocks\nGROUP BY stock_name
SELECT stock_name, SUM(\n    CASE\n    WHEN operation = "Buy" THEN -price\n    ELSE price\n    END) AS capital_gain_loss\nFROM Stocks\nGROUP BY stock_name
[]