๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
SQL/LeetCode

[LeetCode][SQL50] #16. Average Selling Price

by ์ด๋ฎด 2023. 11. 14.
728x90

๐Ÿ’ป ๋ฌธ์ œ ์ฃผ์†Œ : 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 ์ผ๊นŒ?

Prices, UnitsSold ํ…Œ์ด๋ธ”

 

์œ„ input์œผ๋กœ ๋“ค์–ด๊ฐ€๋Š” Prices์™€ UnitsSold ํ…Œ์ด๋ธ”์„ ๋ณด๋ฉด ๋‘ ํ…Œ์ด๋ธ”์„ ์กฐ์ธํ•˜๊ธฐ ์œ„ํ•ด on ์กฐ๊ฑด์œผ๋กœ product_id๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๊นŒ์ง„ ์•Œ๊ฒ ์œผ๋‚˜ ์™œ ๋‘ ๋ฒˆ์งธ ์กฐ๊ฑด์ธ purchase_date ๊ด€๋ จ ๋‚ด์šฉ์ด where์ด ์•„๋‹Œ on์— ํฌํ•จ๋˜์–ด ์žˆ์„๊นŒ? ๊ทธ๊ฒƒ์€ case 2๋ฅผ ๋ณด๋ฉด ์•Œ ์ˆ˜ ์žˆ๋‹ค.

(์ขŒ) case 2์˜ Prices, UnitsSold ํ…Œ์ด๋ธ” (์šฐ) ๊ฒฐ๊ณผ & ๊ธฐ๋Œ€ ํ…Œ์ด๋ธ”

 

์œ„ ์‚ฌ์ง„์„ ๋ณด๋ฉด ์•Œ ์ˆ˜ ์žˆ๋“ฏ 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์„ ํ•œ ์ด์œ ๋„ ์• ๋งคํ•ด์ง„๋‹ค). 

 

728x90
๋ฐ˜์‘ํ˜•