[LeetCode] Average Selling Price

아르당·2026년 4월 13일

LeetCode

목록 보기
257/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

Table: Prices

Column NameType
product_idint
start_datedate
end_datedate
priceint

(product_id, start_date, end_date)는 이 테이블의 기본 키이다.
테이블의 각 행은 start_date와 end_date 기간에 product_id의 price를 나타낸다.
각 product_id는 중복되는 기간이 없다. 같은 product_id는 서료 교차하는 기간이 없는 것을 의미한다.

Table: UnitsSold

Column NameType
product_idint
purchase_datedate
unitsint

이 테이블은 중복된 행이 존재할 수 있다.
테이블의 각 행은 각 판매된 제품의 date, units, product_id를 나타낸다.

각 제품의 평균 판매 가격을 찾는 방법을 작성해라. average_price는 소수점 둘째 자리까지 반올림해야 한다. 판매량이 없는 제품의 가격은 0으로 한다.

Example

Input:
Prices table:

product_idstart_dateend_dateprice
12019-02-172019-02-285
12019-03-012019-03-2220
22019-02-012019-02-2015
22019-02-212019-03-3130

UnitsSold table:

product_idpurchase_dateunits
12019-02-25100
12019-03-0115
22019-02-10200
22019-03-2230

Output:

product_idaverage_price
16.96
216.96

Explanation:
판매 가격의 평균은 제품의 전체 가격 / 판매된 제품의 수이다.
product 1의 판매 가격 평균은 ((100 5) + (15 20)) / 115 = 6.96이다.
product 2의 판매 가격 평균은 ((200 15) + (30 30)) / 230 = 16.96이다.

Solved

-- Write your PostgreSQL query statement below
select A.product_id, round(coalesce((sum(B.units * A.price)::decimal / sum(B.units)), 0.00), 2) as average_price
from Prices A
left outer join UnitsSold B on A.product_id = B.product_id
    and B.purchase_date between A.start_date and A.end_date
group by A.product_id
profile
내 마음대로 코드 작성하는 세상

0개의 댓글