-
카테고리
-
세부 분야
데이터 분석
-
해결 여부
해결됨
쿼리 관련 질문이 있습니다.
23.10.17 00:13 작성 23.10.17 00:20 수정 조회수 196
1
안녕하세요. 강의 듣는 중 궁금한 점이 있어서 질문드립니다.
만약 '카테고리별 기준 월, 전 월, 작년 월 ( 기준 월 = 2023/10, 전월 = 2023/09, 작년 월 = 2022/10)의 차이'를 구하라고 한다면 강의와 같이 기준 연월의 일년 정도의 데이터(2022/10 ~ 2023/10)를 가져와서 사용하는게 더 좋을까요?
아니면, 3개 조건 각각 select하여 카테고리 기준으로 join하는게 더 좋을까요?
ex) with as ( 기준 월), with as (전 월), with as (작년 월)...
혹은 더 좋은 방법이 있다면 알려주시면 감사하겠습니다.
이런 질문 드려도 되는지 모르겠지만.. 강의 잘 듣고 있습니다.
감사합니다.
답변을 작성해보세요.
0
권 철민
지식공유자2023.10.17
안녕하십니까,
잘 듣고 계시다니 저도 기분 좋군요 ^^
제 생각엔 첫번째 방법이 더 좋을 것 같군요. 다만 1년치 데이터를 다 가져오지 않고 in을 사용해서 3개월치 데이터만 가져오면 될 것 같습니다. 다음에 기준월, 이전 월, 일년전월을 구분해서 적용해 보면 될 것 같습니다.
아래는 샘플 SQL입니다. row_number로 되어 있는 부분을 기준월, 이전 월, 일년전월을 구분합니다.
기준월은 1, 이전월은 2, 일년전월은 3 입니다.
with
temp_01 as (
select d.category_name, to_char(date_trunc('month', order_date), 'yyyymm') as month_day
, sum(amount) as sum_amount
, row_number() over (partition by category_name order by to_char(date_trunc('month', order_date), 'yyyymm') desc) as month_gubun
from nw.orders a
join nw.order_items b on a.order_id = b.order_id
join nw.products c on b.product_id = c.product_id
join nw.categories d on c.category_id = d.category_id
where to_char(date_trunc('month', order_date), 'yyyymm') in ('199610','199709', '199710')
group by d.category_name, to_char(date_trunc('month', order_date), 'yyyymm')
)
select category_name
, max(case when month_gubun=1 then sum_amount end) as curr_month_amount
, max(case when month_gubun=2 then sum_amount end) as prev_month_amount
, max(case when month_gubun=3 then sum_amount end) as prev_year_month_amount
from temp_01
group by category_name
감사합니다.
답변 1