문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
Table: Prices
| Column Name | Type |
|---|---|
| product_id | int |
| start_date | date |
| end_date | date |
| price | int |
(product_id, start_date, end_date)는 이 테이블의 기본 키이다.
테이블의 각 행은 start_date와 end_date 기간에 product_id의 price를 나타낸다.
각 product_id는 중복되는 기간이 없다. 같은 product_id는 서료 교차하는 기간이 없는 것을 의미한다.
Table: UnitsSold
| Column Name | Type |
|---|---|
| product_id | int |
| purchase_date | date |
| units | int |
이 테이블은 중복된 행이 존재할 수 있다.
테이블의 각 행은 각 판매된 제품의 date, units, product_id를 나타낸다.
각 제품의 평균 판매 가격을 찾는 방법을 작성해라. average_price는 소수점 둘째 자리까지 반올림해야 한다. 판매량이 없는 제품의 가격은 0으로 한다.
Input:
Prices table:
| product_id | start_date | end_date | price |
|---|---|---|---|
| 1 | 2019-02-17 | 2019-02-28 | 5 |
| 1 | 2019-03-01 | 2019-03-22 | 20 |
| 2 | 2019-02-01 | 2019-02-20 | 15 |
| 2 | 2019-02-21 | 2019-03-31 | 30 |
UnitsSold table:
| product_id | purchase_date | units |
|---|---|---|
| 1 | 2019-02-25 | 100 |
| 1 | 2019-03-01 | 15 |
| 2 | 2019-02-10 | 200 |
| 2 | 2019-03-22 | 30 |
Output:
| product_id | average_price |
|---|---|
| 1 | 6.96 |
| 2 | 16.96 |
Explanation:
판매 가격의 평균은 제품의 전체 가격 / 판매된 제품의 수이다.
product 1의 판매 가격 평균은 ((100 5) + (15 20)) / 115 = 6.96이다.
product 2의 판매 가격 평균은 ((200 15) + (30 30)) / 230 = 16.96이다.
-- 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