Easy-peasy solution with approach explained
We can consider: \n1. All the Buy operations to be "money out" i.e. negative  \n2. All the Sell operations "money in" i.e. positive\n\nSo if we swap the price s
We can consider: \n1. All the Buy operations to be "money out" i.e. *negative*  \n2. All the Sell operations "money in" i.e. *positive*\n\nSo if we swap the price sign for all the rows with the Buy tag, we\'re most of the way there.\n\nThen it\'s just a matter of GROUPing BY the stock_name, and SUMming the prices:\n\n```\nSELECT\n    stock_name,\n    SUM(IF(operation = "Buy", -1*price, price)) \n    # The IF statement here swaps the price sign in the case of a Buy tag, and yes,\n\t# this can be packaged within a sum statement. \n\t\tAS capital_gain_loss\nFROM Stocks\nGROUP BY stock_name\n```
[]