관리 메뉴

오늘도 배운다

1393. Capital Gain/Loss / Leet Code, SQL, MySQL 본문

코딩테스트연습(SQL)

1393. Capital Gain/Loss / Leet Code, SQL, MySQL

LearnerToRunner 2023. 3. 10. 21:03

문제

source: LeetCode
Write an SQL query 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.

 

 

 

 

제출답안(MySQL)

WITH ledger AS(
    SELECT
        stock_name, 
        CASE WHEN 
            operation = 'Buy' THEN price*(-1)
            ELSE price END AS balance
    FROM stocks)

SELECT stock_name, SUM(balance) AS capital_gain_loss
FROM ledger
GROUP BY stock_name

 

 

 

문제 바로가기(MySQL)

728x90
Comments