Simple SQL CASE WHEN solution
Sums all the prices while multiplying the price by 1 if the item is sold and -1 if the item is bought.\n\n\nSELECT \n    stock_name, \n    SUM(price * CASE WHEN
Sums all the prices while multiplying the price by 1 if the item is sold and -1 if the item is bought.\n\n```\nSELECT \n    stock_name, \n    SUM(price * CASE WHEN operation = \'Buy\' THEN -1 ELSE 1 END) capital_gain_loss\nFROM \n    Stocks\nGROUP BY\n    stock_name\n```
['MySQL']