The Stocks table schema is defined as follows:
| Column Name | Type |
|---|---|
| stock_name | varchar |
| operation | enum |
| operation_day | int |
| price | int |
The primary key for this table is the combination of stock_name and operation_day. The operation column is an enumeration containing ('Buy', 'Sell'). Each row represents a transaction made on a specific stock at a given price.
The objective is to calculate the total capital gain or loss for each stock. The capital gain or loss is defined as the difference between the total selling price and the total purchase price for a specific stock.
Example
Input:
| stock_name | operation | operation_day | price |
|---|---|---|---|
| Leetcode | Buy | 1 | 1000 |
| Corona Masks | Buy | 2 | 10 |
| Leetcode | Sell | 5 | 9000 |
| Handbags | Buy | 17 | 30000 |
| Corona Masks | Sell | 3 | 1010 |
| Corona Masks | Buy | 4 | 1000 |
| Corona Masks | Sell | 5 | 500 |
| Corona Masks | Buy | 6 | 1000 |
| Handbags | Sell | 29 | 7000 |
| Corona Masks | Sell | 10 | 10000 |
Output:
| stock_name | capital_gain_loss |
|---|---|
| Corona Masks | 9500 |
| Leetcode | 8000 |
| Handbags | -23000 |
Explanation:
- Leetcode: Bought for 1000 and sold for 9000. Profit = 8000.
- Handbags: Bought for 30000 and sold for 7000. Loss = -23000.
- Corona Masks: Multiple transactions occurred. Net result = (1010-10) + (500-1000) + (10000-1000) = 9500.
Solution
To determine the profit or loss, we can aggregate the price values for each stock. 'Buy' operations represent costs (negative value), while 'Sell' operations represent revenue (positive value). The sum of these values yields the net capital gain or loss.
Option 1: Using CASE expression
SELECT
stock_name,
SUM(
CASE
WHEN operation = 'Buy' THEN -price
ELSE price
END
) AS capital_gain_loss
FROM Stocks
GROUP BY stock_name;
Option 2: Using IF function
SELECT
stock_name,
SUM(IF(operation = 'Buy', -price, price)) AS capital_gain_loss
FROM Stocks
GROUP BY stock_name;