-
Notifications
You must be signed in to change notification settings - Fork 385
Closed
Description
Your LeetCode username
dshgna
Category of the bug
- Question
- Solution
- Language
- Missing Test Cases
Description of the bug
This question does not have test cases for when there is a buy, but no sell. Neither does the description specify what needs to be done in such an instance, which could either be:
- Consider the buy as a loss, regardless if it has been sold (the top-voted answer addresses this)
- Consider only buy-sell pairs, buys with no sells are not considered a loss - my answer below addresses this scenario
Code you used for Submit/Run operation
WITH ops_ranks AS (
SELECT *,
DENSE_RANK() OVER(PARTITION BY stock_name, operation ORDER BY operation_day) AS ops_rnk
FROM Stocks
)
SELECT s1.stock_name,
SUM(s2.price) - SUM(s1.price) AS capital_gain_loss
FROM ops_ranks s1
# Get buy-sell pairs based on their rank
JOIN ops_ranks s2
ON s1.stock_name = s2.stock_name
AND s1.operation = 'Buy'
AND s2.operation = 'Sell'
AND s1.ops_rnk = s2.ops_rnk
GROUP BY 1
Language used for code
SQL
Expected behavior
Include a test case that has buy, but no sell operation:
{"headers":{"Stocks":["stock_name","operation","operation_day","price"]},"rows":{"Stocks":[["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]]}}
Screenshots
N/A
Additional context
N/A