문제 내용
아래와 같은 Table 2개가 있다.
product id의 제품이 팔린 날짜의 price와 팔린 units 갯수를 곱하고 unit 하나당 팔린 가격의 평균을 구하는 query를 작성하라
접근 방법
1. 두개의 Table을 join 한다
select *
from Prices a,UnitsSold b
where a.product_id = b.product_id
select *
FROM Prices as a
JOIN UnitsSold as b
ON a.product_id=b.product_id
위에 두개는 동일한 inner join이다.
2. purchase_date가 start_date와 end_date 사이에 있는 경우만 추출한다.
select *
from Prices a,UnitsSold b
where a.product_id = b.product_id
and b.purchase_date between a.start_date and a.end_date
SELECT *
FROM Prices as a
JOIN UnitsSold as b
ON a.product_id=b.product_id AND (b.purchase_date BETWEEN a.start_date AND a.end_date)
3. product_id로 group by 처리 한다.
하기와 같이 2가지로 개발 가능하다.
select rst.product_id, round(sum(rst.price)/sum(rst.units),2) as average_price
from (
select a.product_id, a.price * b.units as price, b.units units
from Prices a, UnitsSold b
where a.product_id = b.product_id
and b.purchase_date between a.start_date and a.end_date
) rst
group by product_id
SELECT a.product_id,ROUND(SUM(b.units*a.price)/SUM(b.units),2) as average_price
FROM Prices as a
JOIN UnitsSold as b
ON a.product_id=b.product_id AND (b.purchase_date BETWEEN a.start_date AND a.end_date)
GROUP BY product_id;
오랫만에 sql 하는것도 재미있네 종종 풀어야 겠다.
728x90
반응형
'Problem Solving' 카테고리의 다른 글
Minimum Number of Increments on Subarrays to Form a Target Array (0) | 2021.07.24 |
---|---|
990. Satisfiability of Equality Equations (0) | 2021.07.22 |
Find Center of Star Graph (0) | 2021.07.14 |
Edit Distance (Levenshtein 알고리즘) (0) | 2021.07.07 |
One Edit Distance (0) | 2021.07.05 |