• 카테고리

    질문 & 답변
  • 세부 분야

    데이터베이스

  • 해결 여부

    미해결

상품 매출 순위 10% 상품 및 매출액 질문

22.06.25 17:52 작성 조회수 155

0

안녕하세요.
마지막 문제 풀 때 아래와 같은 쿼리로 해도 같은 결과가 나오는데
아래와 같이 with절을 써도 될까요?
인라인 서브쿼리를 사용하는 경우와 with절을 사용하는 경우가 있는데 이 둘의 차이를 알려주시면 감사드리겠습니다!
 
with temp_01 as
(
select product_id, sum(amount) as sum_amount
from order_items
group by product_id
order by 1 ), temp_02 as(
select a.product_id, a.sum_amount, b.product_name
, cume_dist()over(order by sum_amount asc) as cume_amount
from temp_01 a
join products b on a.product_id = b.product_id
)
select *
from temp_02 where cume_amount >= 0.9

답변 1

답변을 작성해보세요.

2

안녕하십니까, 

네, 물론입니다. 인라인 서브쿼리 대신 with 절을 사용하셔도 무방합니다. 

인라인 서브쿼리와 with절은 거의 동일합니다. 다만 with절은 인라인 서브쿼리의 약간(?)의 문제점을 대체하기 위해서 나온것인데, With 절의 집합을 SQL 전체에서 사용할 때는 해당 집합을 얼마든지 With 절에 as로 명시된 집합명으로 사용할 수 있는데 반해서 인라인 서브쿼리는 그렇지 못하다는 차이가 있습니다. 

가령 with 절의 집합을  self 조인하면 아래와 같이 with 절의 as 집합명을 이용하여 쉽게 가능하지만  

with 

temp_01 as ( 

select product_id, sum(amount) as sum_amount

from nw.orders a 

join nw.order_items b 

on a.order_id = b.order_id

group by product_id

)

select * from temp_01 a, temp_01 b 

where a.product_id = b.product_id;

 

인라인 서브쿼리의 경우는 해당 집합을 아래와 같이 중복해서 명시해 줘야 합니다. 

select * from 

(select product_id, sum(amount) as sum_amount

from nw.orders a 

join nw.order_items b 

on a.order_id = b.order_id

group by product_id

) a, 

(select product_id, sum(amount) as sum_amount

from nw.orders a 

join nw.order_items b 

on a.order_id = b.order_id

group by product_id 

) b

where a.product_id = b.product_id;

April Kang님의 프로필

April Kang

질문자

2022.06.27

두 질문 모두 이해했습니다! 친절하게 설명해주셔서 감사드립니다! :)