๐ป ๋ฌธ์ ์ฃผ์ : Average Selling Price - LeetCode
Average Selling Price - LeetCode
Can you solve this real interview question? Average Selling Price - Table: Prices +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | start_date | date | | end_date | date | | price | int | +---------------
leetcode.com
๐ป ๋ฌธ์
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
- ๊ฐ ์ํ๋ณ ํ๊ท ๋งค์ถ์ก์ ๊ตฌํ์์ค. average_price๋ ์์์ ๋ ์๋ฆฌ๊น์ง ์ถ๋ ฅ๋์ด์ผ ํ๋ฉฐ, ์ถ๋ ฅ ์์๋ ์๊ด ์์ต๋๋ค.
๐ป ์ฝ๋ ๋ฐ ํ์ด
select p.product_id, ifnull(round(sum(units*price)/sum(units), 2), 0) as average_price
from Prices p
left join UnitsSold u
on p.product_id = u.product_id and u.purchase_date between p.start_date and p.end_date
group by product_id
โ ๋ฌธ์ ํ์ด ํต์ฌ : ์ where์ด ์๋๋ผ on ์ผ๊น?
์ input์ผ๋ก ๋ค์ด๊ฐ๋ Prices์ UnitsSold ํ ์ด๋ธ์ ๋ณด๋ฉด ๋ ํ ์ด๋ธ์ ์กฐ์ธํ๊ธฐ ์ํด on ์กฐ๊ฑด์ผ๋ก product_id๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๊น์ง ์๊ฒ ์ผ๋ ์ ๋ ๋ฒ์งธ ์กฐ๊ฑด์ธ purchase_date ๊ด๋ จ ๋ด์ฉ์ด where์ด ์๋ on์ ํฌํจ๋์ด ์์๊น? ๊ทธ๊ฒ์ case 2๋ฅผ ๋ณด๋ฉด ์ ์ ์๋ค.
์ ์ฌ์ง์ ๋ณด๋ฉด ์ ์ ์๋ฏ case 2์ Prices ํ ์ด๋ธ์ ๊ฒฝ์ฐ, product_id๊ฐ 3์ธ ๋ฐ์ดํฐ๊ฐ ์์ผ๋ UnitsSold์๋ 1, 2๋ง ์๋ค. ์ด ๊ฒฝ์ฐ, where์ ์ purchase_date between start_date and end_date๋ฅผ ํ ๊ฒฝ์ฐ, product_id 3์ธ ๋ฐ์ดํฐ๋ฅผ ํํฐ๋งํ๊ฒ ๋์ด product_id 3์ธ ๊ฒฝ์ฐ์ ๋ํ ํ๊ท ๋งค์ถ์ก์ ๊ตฌํ ์ ์๋ค (left join์ ํ ์ด์ ๋ ์ ๋งคํด์ง๋ค).
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode][SQL50] #18. Percentage of Users Attended a Contest (0) | 2023.11.15 |
---|---|
[LeetCode][SQL50] #17. Project Employees I (0) | 2023.11.15 |
[LeetCode][SQL50] #15. Not Boring Movies (2) | 2023.11.13 |
[LeetCode][SQL50] #14. Confirmation Rate (0) | 2023.11.13 |
[LeetCode][SQL50] #13. Managers with at Least 5 Direct Reports (0) | 2023.11.09 |