Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[Leet code] 1393. Capital Gain/Loss

์ธ” 2023. 10. 4. 03:41

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ 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

 

'Growth ๐ŸŒณ > Practice ๐Ÿ’ป' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leet code] 1075. Project Employees I  (1) 2023.10.06
[Leet code] 1934. Confirmation Rate  (1) 2023.10.05
[Leet code] 1204. Last Person to Fit in the Bus  (0) 2023.09.26
1907. Count Salary Categories  (0) 2023.09.24
[Leet code] 1341. Movie Rating  (1) 2023.09.22