2 Simple SQL Solutions using SUM IF or CASE
Using a CASE statement\n\nSELECT stock_name,\nSUM(CASE\n        WHEN operation = \'Buy\' THEN -1*price\n        ELSE price\n   END)\nAS capital_gain_loss FROM S
**Using a CASE statement**\n```\nSELECT stock_name,\nSUM(CASE\n        WHEN operation = \'Buy\' THEN -1*price\n        ELSE price\n   END)\nAS capital_gain_loss FROM Stocks\nGROUP BY stock_name\n```\n\n**Using a IF condition**\n```\nSELECT stock_name,\nSUM(IF(operation = \'Buy\', -1*price, price))\nAS capital_gain_loss FROM Stocks\nGROUP BY stock_name\n```
['MySQL', 'MS SQL Server']