🤍 전 강의 25% 할인 중 🤍

2024년 상반기를 돌아보고 하반기에도 함께 성장해요!
인프런이 준비한 25% 할인 받으러 가기 >>

  • 카테고리

    질문 & 답변
  • 세부 분야

    데이터 분석

  • 해결 여부

    미해결

집계 함수 order by

23.07.20 12:53 작성 조회수 190

0

with temp_01

as (

select d.category_name,

to_char(date_trunc('month', a.order_date), 'yyyymm') as month_day,

sum(amount) as sum_amount,

count(distinct a.order_id) as monthly_ord_cnt

from orders a

join order_items b on a.order_id = b.order_id

join products c on b.product_id = c.product_id

join categories d on c.category_id = d.category_id

group by d.category_name, to_char(date_trunc('month', a.order_date), 'yyyymm')

)

select *,

sum(sum_amount) over (partition by month_day order by month_day) as temp1,

sum(sum_amount) over (partition by month_day) as temp2,

sum_amount / sum(sum_amount) over (partition by month_day) as ratio

from temp_01

집계 어날리틱 함수는 order by를 사용하면 파티션 내에서 누적합이 되는것으로 알고 있었는데 왜 이렇게 나올까요...? 제가 혹시 놓친게 있는 걸까요

답변 1

답변을 작성해보세요.

1

analytic 사용시 partition by month_day order by month_day와 같이 partition by와 orderby의 컬럼이 모두 month_day로 같습니다. month_day로 partition이 되면 동일한 month_day가 모이게 되는데, 이 동일한 month_day에서 다시 order by month_day는 모두 동일한 month_day이기 때문에 총합이 나오게 됩니다(즉 ordering 순서가 다 동일합니다)

아래와 같이 다른 컬럼으로 order by를 수행하면 누적합이 됩니다.

sum(sum_amount) over (partition by month_day order by sum_amount) as temp1,

 

정성훈님의 프로필

정성훈

질문자

2023.07.23

partition 절과 order by 절에 같은 컬럼을 대상으로 한다면 해당 파티션의 총합이 된다고 생각하면 무리가 없을까요?

채널톡 아이콘