데이터 분석

1393. Capital Gain/Loss | Medium 💡 본문

SQL/leetcode

1393. Capital Gain/Loss | Medium 💡

딱한아이 2025. 2. 17. 22:19
문제

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.

테이블 정보

 

예시

 

주식에 대한 각 'Sell' 작업은 이전 날에 해당하는 'Buy' 작업이 반드시 존재한다. 이 점을 참고하여, 하나의 주식을 한 번 또는 여러 번 사고판 후의 총 이익 또는 손실을 계산한다.

 

 

Solution
SELECT stock_name
     , SUM(CASE WHEN operation = 'Buy' then -price 
                ELSE price 
           END) AS capital_gain_loss
FROM stocks
GROUP BY stock_name

 

✅ 주식이 '구매'된 경우에는 가격을 음수로 변환하고, '판매'된 경우에는 양수로 유지하여 수익으로 처리한다.

✅ 결과적으로 '판매' 가격에서 '구매' 가격을 빼는 연산이 이루어진다. 

'SQL > leetcode' 카테고리의 다른 글

1158. Market Analysis 1 | Medium 💡  (0) 2025.02.19
601. Human Traffic of Stadium | Hard 🔥  (0) 2025.02.18
1321. Restaurant Growth | Medium 🔥  (1) 2025.02.01
178. Rank Scores | Medium  (0) 2025.02.01
185. Department Top Three Salaries | Hard  (1) 2025.02.01