[Leet code] 1393. Capital Gain/Loss
๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ๋ฌธ์
https://leetcode.com/problems/capital-gainloss/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Table : Stocks
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.
The result format is in the following example.
โ ํ์ด
๋ฌธ์ ์๊ตฌ์ฌํญ
operation ์ปฌ๋ผ์ 'ํ๋งค(Sell)' ๋๋ '๊ตฌ๋งค(Buy)'๋ฅผ ๊ฐ์ผ๋ก ๊ฐ๋๋ค
๊ฐ ํ์ stock_name์ ๊ฐ๋ ๊ฐ ์ฃผ์์ด Operation_day์ ํด๋น price๋ก ๊ฑฐ๋๋์์์ ๋ํ๋ธ๋ค.
๊ฐ ์ฃผ์์ ์๋ณธ ์ด๋/์์ค์ ์ถ๋ ฅํด์ผ ํ๋ค.
โ ์ฃผ์๋ณ๋ก ์ฝ๊ฒ ์ง๊ณํ๊ธฐ ์ํด ์ฐ์ FROM์ ์๋ธ์ฟผ๋ฆฌ์ ์ฃผ์๋ณ ์ผ์์ ๋งค์-๋งค๋์์ผ๋ก ์ ๋ ฌํ T1 ํ ์ด๋ธ์ ๋ง๋ค์ด์ฃผ์๊ณ
โก T1 ํ ์ด๋ธ์์ stock_name์ ๊ธฐ์ค์ผ๋ก ๊ทธ๋ฃนํํด์ ์ ์ฒด ๋งค๋ price์ ์ ์ฒด ๋งค์ price๋ฅผ CASE๋ฌธ์ผ๋ก ๊ตฌ๋ถํ ํ ๊ฐ๊ฐ์ ์ง๊ณ ์ฐจ์ด๋ฅผ capital_gain_loss๋ก ์ถ๋ ฅํ๋ค.
SELECT stock_name,
SUM((CASE WHEN operation = 'Sell' THEN price ELSE 0 END))
- SUM((CASE WHEN operation = 'Buy' THEN price ELSE 0 END)) AS capital_gain_loss
FROM (SELECT *
FROM Stocks
ORDER BY 1, 3, 2) T1
GROUP BY 1
โ ๋ฌธ์ ํ์ด ํ๊ณ
์ฃผ์๋ณ๋ก ์ ์ฒด ๋งค์ ํฉ๊ณผ ๋งค์ ํฉ์ฐจ๋ฅผ ๊ตฌํ๋ ๋ฐฉ์์ด ์๋๋ผ ์ฃผ์๋ณ๋ก ๊ฑฐ๋์ผ์ ์์ผ๋ก ๋งค์-๋งค๋ ๊ฐ์ ์์ฐจ์ ์ผ๋ก ๊ณ์ฐํ ์ ์๋ ๋ฐฉ๋ฒ(ํจ์)์ด ์์ ๊ฒ ๊ฐ๋ค. ์๋ก์ด 2์ฐจ ํ์ด๋ ์๊ฐํด๋ด์ผ๊ฒ ๋ค.
- 23.10.05 ์ถ๊ฐ
2์ฐจ ํ์ด) CASE๋ฌธ
์์ต์ด๋ผ๋ ๊ฐ๋ ์ ๊ฐ๋ ๋๋ก -, + ๋ก ์๊ฐํด๋ณด๋ฉด, CASE๋ฌธ๊ณผ ์ง๊ณ๋ฅผ ๊ตณ์ด ๋๋ฒ ํ ํ์๊ฐ ์์๋ค. ๐ฒ ํ๋ฒ์ CASE๋ฌธ์์ ๋งค์/๋งค๋์ ๋ฐ๋ผ +-๋ก price ๊ฐ์ ๋๋ ์ค ํ ์ง๊ณํด์ฃผ๋ฉด ๋ ๊ฐ๋จํ๊ฒ ํ ์ ์๋ค.
SELECT stock_name,
SUM(CASE WHEN operation = 'Buy' THEN -price
ELSE price END
) AS capital_gain_loss
FROM Stocks
GROUP BY 1