Skip to content

Commit 44b20b2

Browse files
committed
task: #1393
1 parent 6383d2e commit 44b20b2

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ Useful for preparing for technical interviews and improving your SQL skills.
171171
- [1204. Last Person to Fit in the Bus](./leetcode/medium/1204.%20Last%20Person%20to%20Fit%20in%20the%20Bus.sql)
172172
- [1321. Restaurant Growth](./leetcode/medium/1321.%20Restaurant%20Growth.sql)
173173
- [1341. Movie Rating](./leetcode/medium/1341.%20Movie%20Rating.sql)
174+
- [1393. Capital Gain/Loss](./leetcode/medium/1393.%20Capital%20Gain&Loss.sql)
174175
- [1907. Count Salary Categories](./leetcode/medium/1907.%20Count%20Salary%20Categories.sql)
175176
- [1934. Confirmation Rate](./leetcode/medium/1934.%20Confirmation%20Rate.sql)
176177
- [3475. DNA Pattern Recognition](./leetcode/medium/3475.%20DNA%20Pattern%20Recognition.sql)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Question 1393. Capital Gain/Loss
3+
Link: https://leetcode.com/problems/capital-gainloss/description/?envType=problem-list-v2&envId=database
4+
5+
Table: Stocks
6+
7+
+---------------+---------+
8+
| Column Name | Type |
9+
+---------------+---------+
10+
| stock_name | varchar |
11+
| operation | enum |
12+
| operation_day | int |
13+
| price | int |
14+
+---------------+---------+
15+
(stock_name, operation_day) is the primary key (combination of columns with unique values) for this table.
16+
The operation column is an ENUM (category) of type ('Sell', 'Buy')
17+
Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price.
18+
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.
19+
20+
21+
Write a solution to report the Capital gain/loss for each stock.
22+
23+
The Capital gain/loss of a stock is the total gain or loss after buying and selling the stock one or many times.
24+
25+
Return the result table in any order.
26+
*/
27+
28+
-- with subqueries
29+
30+
SELECT DISTINCT
31+
s.stock_name,
32+
(
33+
SELECT SUM(s1.price)
34+
FROM Stocks AS s1
35+
WHERE s1.stock_name = s.stock_name AND s1.operation = 'Sell'
36+
)
37+
- (
38+
SELECT SUM(s2.price)
39+
FROM Stocks AS s2
40+
WHERE s2.stock_name = s.stock_name AND s2.operation = 'Buy'
41+
)
42+
AS capital_gain_loss
43+
FROM Stocks AS s

0 commit comments

Comments
 (0)