๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ 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 |