[ORACLE_SQL](Leet_Code)1251. Average Selling Price

이경영·2023년 8월 3일
0

오라클

목록 보기
35/43

문제요약

  1. Units Sold의 purchase_date가 Prices의 start_date와 end_date사이에 있고, 두 product_id가 동일한경우를 구하고
  2. 그 product_id의 평균을 구하여라 (가격*수량)/수량

핵심포인트

  • inner join, group by, where

방법

두 테이블을 이너조인한다.
첫번째 방안을 처음에는 case when 으로 푸려고했다. 그러나 이러한 경우는 두 컬럼으로 무엇인가를 구하는게 아니라, 그 컬럼 자체를 뽑는것이기 때문에 where문으로 처리해주어야 한다.
나에게 두번째가 어려웠다. 이걸 어떻게 평균을 구해야하지? product_id가 1인것은 row가 두개나오는데..

이러한 경우에는 그룹바이를 생각해내야했다.. ^^정말바보....

정답

select a.product_id, round(sum(a.price * b.units)/sum(units),2) as average_price
  from Prices a inner join UnitsSold b
  on a.product_id=b.product_id
  where b.purchase_date between a.start_date and a.end_date
group by a.product_id
profile
꾸준히

0개의 댓글