작성
·
214
0
-- 직원별 개별 상품 매출액, 직원별 가장 높은 상품 매출액을 구하고, 직원별로 가장 높은 매출을 올리는 상품의 매출 금액 대비 개별 상품 매출 비율 구하기
with
temp_01 as (
select b.employee_id, a.product_id, sum(amount) as sum_by_emp_prod
from order_items a
join orders b on a.order_id = b.order_id
group by b.employee_id, a.product_id
)
select employee_id, product_id, sum_by_emp_prod
, max(sum_by_emp_prod) over (partition by employee_id) as sum_by_emp
, sum_by_emp_prod/max(sum_by_emp_prod) over (partition by employee_id) as sum_ratio
from temp_01
order by 1, 5 desc;
위 쿼리의 실행 순서를 살펴 보았는데 맞는지 조언 얻고 싶습니다.
order_items a와 orders b를 order_id로 join
1의 결과를 employee_id로 group by
select b.employee_id, a.product_id select하여 temp_01 완성
temp_01에서 employee_id, product_id, sum_by_emp_prod, sum_by_emp, sum_ratio를 select
1, 5요인으로 desc 하여 order by
또 sum_ratio를 select 할 때 sum_by_emp를 사용하지 않고 max(sum_by_emp_prod) over (partition by employee_id)를 그대로 쓰는 이유가 궁금합니다
답변 1
0
order_items a와 orders b를 order_id로 join
1의 결과를 employee_id로 group by
select b.employee_id, a.product_id select하여 temp_01 완성
temp_01에서 employee_id, product_id, sum_by_emp_prod, sum_by_emp, sum_ratio를 select
1, 5요인으로 desc 하여 order by
네, 다 맞습니다. 다만 2의 경우 employee_id, product_id로 group by 합니다.
그리고 아래 질문은
sum_ratio를 select 할 때 sum_by_emp를 사용하지 않고 max(sum_by_emp_prod) over (partition by employee_id)를 그대로 쓰는 이유가 궁금합니다
=> select 절에 사용된 max(sum_by_emp_prod) over (partition by employee_id)로 만들어진 alias는 동일한 select절의 다른 컬럼에서 사용될 수 없습니다. 때문에 max(sum_by_emp_prod) over (partition by employee_id)를 두번 사용하였습니다.
감사합니다.