하나의 SQL 쿼리에서 두 개의 COUNT 병합

Aug 29 2020

new_customers X customers_cancellations를 표시하기 위해 쿼리를 수행해야합니다.

이 쿼리를 사용하면 월별로 new_customers를 얻을 수 있습니다.

count (start_date), to_char (start_date, 'MM')을 monthNumber로, to_char (start_date, 'YY')를 yearNumber로 선택 
start_date가 null이 아닌 고객 
to_char (start_date, 'MM'), to_char (start_date, 'YY')별로 그룹화 
yearNumber, monthNumber로 주문;

이 외에 월별 고객 취소를받을 수 있습니다.

count (cancellation_date), to_char (cancellation_date, 'MM')을 monthNumber로, to_char (cancellation_date, 'YY')를 yearNumber로 선택
cancel_date가 null이 아닌 고객 
to_char (cancellation_date, 'MM'), to_char (cancellation_date, 'YY')별로 그룹화 
yearNumber, monthNumber로 주문;

두 쿼리 모두 다음과 같은 결과를 반환합니다.

카운트 | 월 번호 | 연수
1 | 1 | 20
7 | 2 | 20
5 | 3 | 20

하지만 다음과 같이 싶습니다.

customer_out_count | customer_in_count | 월 번호 | 연수
 0 | 1 | 1 | 20
 0 | 7 | 2 | 20
 1 | 0 | 3 | 20
 0 | 1 | 4 | 20
 5 | 7 | 5 | 20
 1 | 5 | 6 | 20

이 다른 쿼리를 이미 시도했습니다.

유형으로 'start'를 선택하고, count (start_date)를 개수로, to_char (start_date, 'MM')을 monthNumber로, to_char (start_date, 'YY')를 yearNumber로 선택
start_date가 null이 아닌 고객
to_char (start_date, 'MM'), to_char (start_date, 'YY')별로 그룹화
노동 조합
유형으로 'cancellation'을 선택하고 counta로 count (cancellation_date)를 선택하고 yearNumber로 to_char (cancellation_date, 'MM')을, yearNumber로 to_char (cancellation_date, 'YY')를 선택합니다.
cancel_date가 null이 아닌 고객
to_char (cancellation_date, 'MM'), to_char (cancellation_date, 'YY')별로 그룹화
yearNumber, monthNumber로 주문;

결과는 "OK"입니다.

유형 | newcount | 월 번호 | 연수
 시작 | 1 | 1 | 20
 취소 | 1 | 1 | 20
 취소 | 7 | 2 | 20
 시작 | 3 | 3 | 20
 취소 | 1 | 4 | 20
 시작 | 7 | 5 | 20
 시작 | 5 | 6 | 20

그러나 필요한 것을 달성하기 위해 코드에서 몇 가지 작업을 수행해야합니다.

이 두 쿼리를 하나로 병합하려면 어떻게해야합니까? postgreslq를 사용하고 있습니다.

답변

1 GMB Aug 29 2020 at 06:30

한 가지 옵션은 행을 피벗 해제 한 다음 집계합니다. Postgres에서는이를 측면 조인으로 표현합니다.

select
    sum(x.customer_in_count)  as customer_in_count,
    sum(x.customer_out_count) as customer_out_count
    to_char(x.dt, 'MM') as monthNumber, 
    to_char(x.dt, 'YY') as yearNumber
from customer c
cross join lateral (values
    (c.start_date, 1, 0), (c.cancellation_date, 0, 1)
) as x(dt, customer_in_count, customer_out_count)
where x.dt is not null
group by monthNumber, yearNumber
order by monthNumber, yearNumber