diff --git a/README.md b/README.md index f2de167..71f6325 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ Useful for preparing for technical interviews and improving your SQL skills. - [1204. Last Person to Fit in the Bus](./leetcode/medium/1204.%20Last%20Person%20to%20Fit%20in%20the%20Bus.sql) - [1321. Restaurant Growth](./leetcode/medium/1321.%20Restaurant%20Growth.sql) - [1341. Movie Rating](./leetcode/medium/1341.%20Movie%20Rating.sql) + - [1393. Capital Gain/Loss](./leetcode/medium/1393.%20Capital%20Gain&Loss.sql) - [1907. Count Salary Categories](./leetcode/medium/1907.%20Count%20Salary%20Categories.sql) - [1934. Confirmation Rate](./leetcode/medium/1934.%20Confirmation%20Rate.sql) - [3475. DNA Pattern Recognition](./leetcode/medium/3475.%20DNA%20Pattern%20Recognition.sql) diff --git a/leetcode/medium/1393. Capital Gain&Loss.sql b/leetcode/medium/1393. Capital Gain&Loss.sql new file mode 100644 index 0000000..b60603d --- /dev/null +++ b/leetcode/medium/1393. Capital Gain&Loss.sql @@ -0,0 +1,43 @@ +/* +Question 1393. Capital Gain/Loss +Link: https://leetcode.com/problems/capital-gainloss/description/?envType=problem-list-v2&envId=database + +Table: Stocks + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| stock_name | varchar | +| operation | enum | +| operation_day | int | +| price | int | ++---------------+---------+ +(stock_name, operation_day) is the primary key (combination of columns with unique values) for this table. +The operation column is an ENUM (category) of type ('Sell', 'Buy') +Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price. +It is guaranteed that each 'Sell' operation for a stock has a corresponding 'Buy' operation in a previous day. It is also guaranteed that each 'Buy' operation for a stock has a corresponding 'Sell' operation in an upcoming day. + + +Write a solution to report the Capital gain/loss for each stock. + +The Capital gain/loss of a stock is the total gain or loss after buying and selling the stock one or many times. + +Return the result table in any order. +*/ + +-- with subqueries + +SELECT DISTINCT + s.stock_name, + ( + SELECT SUM(s1.price) + FROM Stocks AS s1 + WHERE s1.stock_name = s.stock_name AND s1.operation = 'Sell' + ) + - ( + SELECT SUM(s2.price) + FROM Stocks AS s2 + WHERE s2.stock_name = s.stock_name AND s2.operation = 'Buy' + ) + AS capital_gain_loss --noqa: LT02 +FROM Stocks AS s