Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[Leet Code] 1251. Average Selling Price

์ธ” 2023. 10. 18. 23:52

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

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โœ”๋ฌธ์ œ

https://leetcode.com/problems/students-and-examinations/description/

 

Students and Examinations - LeetCode

Can you solve this real interview question? Students and Examinations - Table: Students +---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | student_name | varchar | +---------------+---------+ student_id is

leetcode.com

 

Table : Prices

Table : UnitsSold

Write a solution to find the average selling price for each product. average_price should be rounded to 2 decimal places. Return the result table in any order.


โœ” ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

 

Prices ํ…Œ์ด๋ธ”์€ ์ƒํ’ˆ๋ณ„ id, ํŒ๋งค๊ธฐ๊ฐ„, ํŒ๋งค๊ฐ€๊ฒฉ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•œ๋‹ค.

UnitSold ํ…Œ์ด๋ธ”์€ ์ƒํ’ˆ๋ณ„ id, ํŒ๋งค๋‚ ์งœ, ๊ฐœ์ˆ˜ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•œ๋‹ค.

๋‘ ํ…Œ์ด๋ธ”์„ ์กฐ์ธํ•ด์„œ ๊ฐ ์ƒํ’ˆ๋ณ„ ํ‰๊ท  ํŒ๋งค๊ฐ€๊ฒฉ์„ ์ถœ๋ ฅํ•˜๋˜, ํ‰๊ท  ๊ฐ€๊ฒฉ์€ ์†Œ์ˆ˜์  2์ž๋ฆฌ๊นŒ์ง€ ๋ฐ˜์˜ฌ๋ฆผํ•˜์—ฌ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

 

โ€ป ํ…Œ์ด๋ธ”์„ ์กฐ์ธํ•˜๊ธฐ ์ „์— ์ƒ๊ฐํ•ด๋ด์•ผ ํ•  ์ ์€ ์ „์ฒด ์ƒํ’ˆ์ด ๋ชจ๋‘ ํŒ๋งค๋˜์ง€๋Š” ์•Š์•˜์„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

โ‘  ๋”ฐ๋ผ์„œ UnitsSold ํ…Œ์ด๋ธ”์—์„œ ํŒ๋งค๋˜์ง€ ์•Š์€ ์ƒํ’ˆ์ด Prices์— ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ LEFT JOIN์œผ๋กœ ์กฐ์ธ

โ‘ก ์กฐ์ธ ์กฐ๊ฑด์ค‘ UnitsSold ์˜ ํŒ๋งค๋‚ ์งœ๊ฐ€ Prices ์˜ ํŒ๋งค๊ธฐ๊ฐ„ ๋‚ด ์กด์žฌํ•ด์•ผ ํ•œ๋‹ค๋Š” ์กฐ๊ฑด์„ BETWEEN ๊ตฌ๋ฌธ์œผ๋กœ ์„ค์ •

โ‘ข ์ฟผ๋ฆฌ ์‹คํ–‰์ˆœ์„œ์—์„œ < โ‘  >์— ์˜ํ•ด ํ‰๊ท ๊ฐ€๊ฒฉ ์ง‘๊ณ„๊ฐ€ ์ ์šฉ๋˜์ง€ ์•Š๊ณ  ๊ทธ๋Œ€๋กœ Null๊ฐ’์ด ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” average_price์— ๋Œ€ํ•ด์„œ๋Š” IFNULLํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ 0 ์ฒ˜๋ฆฌ ํ•ด์ฃผ์—ˆ๋‹ค. 

 

์ƒํ’ˆ๋ณ„ ํ‰๊ท ๊ฐ€๊ฒฉ = ∑ ( ์ƒํ’ˆ๊ฐ€๊ฒฉ × ํŒ๋งค๊ฐ€๊ฒฉ ) / ∑(ํŒ๋งค๊ฐœ์ˆ˜)

SELECT p.product_id, IFNULL(ROUND(SUM(p.price * us.units)/SUM(us.units), 2),0) AS average_price
 FROM Prices p
 LEFT JOIN UnitsSold us
 ON p.product_id = us.product_id
 AND (us.purchase_date BETWEEN p.start_date AND p.end_date)
 GROUP BY 1;

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

[Leet Code] 1148. Article Views I  (0) 2023.10.21
[Leet Code] 1407. Top Travellers  (1) 2023.10.20
[Leet Code] 1280. Students and Examinations  (0) 2023.10.17
[Leet Code] 1965. Employees With Missing Information  (0) 2023.10.12
[Leet code] 1978. Employees Whose Manager Left the Company  (0) 2023.10.11