programing

순차적인 월별 리드를 SQL의 열로 계산하시겠습니까?

padding 2023. 7. 27. 21:41
반응형

순차적인 월별 리드를 SQL의 열로 계산하시겠습니까?

각 회사의 월별 리드 수를 끌어내려고 노력하고 있습니다.다음과 같은 쿼리를 사용하여 모든 개별 달에 대해 이를 수행할 수 있습니다.

MONTH 1 LEAD COUNTS
select l.companyProfileID, count(l.id) as 'Month 1 LC'
from lead l
join companyProfile cp on cp.id = l.companyProfileID
where l.createTimestamp between cp.createTimestamp and date_sub(cp.createTimestamp, INTERVAL -1 month)
group by companyProfileID

MONTH 2 LEAD COUNTS
select l.companyProfileID, count(l.id) as 'Month 2 LC'
from lead l
join companyProfile cp on cp.id = l.companyProfileID
where l.createTimestamp between date_sub(cp.createTimestamp, INTERVAL -1 month) and date_sub(cp.createTimestamp, INTERVAL -2 month)
group by companyProfileID

하지만 12개의 서로 다른 쿼리를 실행하여 연간 리드 수를 얻는 대신 열이 있는 단일 테이블을 만들고 싶습니다. 회사 프로파일ID, 1월 LC, 2월 LC 등.

내장된 선택 기능이 필요할 수도 있지만 SQL을 바로 배우고 있습니다.어떻게 하면 이를 달성할 수 있을까요?

여러 쿼리를 실행하는 대신 "조건부 집계"를 사용할 수 있습니다.실질적으로 당신은 당신의 전류를 움직이며, 여기서 집합 내부의 조건들이 함수를 형성합니다.case expression참고:count()함수가 NULL을 무시합니다.

select 
        l.companyProfileID
      , count(case when l.createTimestamp between cp.createTimestamp 
                    and date_sub(cp.createTimestamp, INTERVAL -1 month) then 1 end) as 'Month 1 LC'
      , count(case when l.createTimestamp between date_sub(cp.createTimestamp, INTERVAL -1 month)
                    and date_sub(cp.createTimestamp, INTERVAL -2 month) then 1 end) as 'Month 2 LC'

      ... more (similar to the above)

      , count(case when l.createTimestamp between date_sub(cp.createTimestamp, INTERVAL -11 month)
                    and date_sub(cp.createTimestamp, INTERVAL -12 month) then 1 end) as 'Month 12 LC'
from lead l
join companyProfile cp on cp.id = l.companyProfileID
where l.createTimestamp between cp.createTimestamp and date_sub(cp.createTimestamp, INTERVAL -12 month)
group by companyProfileID

또한 "사이"에는 첫 번째 날짜가 두 번째 날짜보다 빨라야 합니다. 예를 들어 다음은 행을 반환하지 않습니다.

select * from t where datecol between 2018-01-01 and 2017-01-01

그러나 이 방법은 다음과 같습니다.

select * from t where datecol between 2017-01-01 and 2018-01-01

언급URL : https://stackoverflow.com/questions/48308386/pulling-sequential-monthly-lead-counts-as-columns-in-sql

반응형