1

조치 A 또는 조치 B를 한 # 명의 사용자를 매월 찾으려고합니다.generate_series 및 count에 가입하십시오.

테이블 : 사용자 - ID - "에서 CreationDate"

테이블 : action_A - USER_ID (= user.id) - "에서 CreationDate"

테이블 : action_B - USER_ID (= 사용자. id) - "creationDate"

내가하려는 일의 일반적인 아이디어는 달 X에 작업 A를 수행 한 사용자 목록과 달 X에 작업 B를 수행 한 사용자 목록을 찾을 수 있다는 것입니다 , 그 다음에 엄마가 어떻게 계산되는지 뉴욕 ID는 매달 날짜의 generate_series를 기반으로 매달 존재합니다.

나는 다음을 시도했다. 그러나 실행 중에 쿼리 시간이 초과되었고 최적화 할 수있는 방법이 있는지 (또는 올바른지 여부) 확실하지 않다.

SELECT monthseries."Month", count(*) 
FROM 
    (SELECT to_char(DAY::date, 'YYYY-MM') AS "Month" 
    FROM generate_series('2014-01-01'::date, CURRENT_DATE, '1 month') DAY) monthseries 
LEFT JOIN 
    (SELECT to_char("creationDate", 'YYYY-MM') AS "Month", 
      id 
    FROM action_A) did_action_A ON monthseries."Month" = did_action_A."Month" 
LEFT JOIN 
    (SELECT to_char("creationDate", 'YYYY-MM') AS "Month", 
      id 
    FROM action_B) did_action_B ON monthseries."Month" = did_action_B."Month" 
GROUP BY monthseries."Month" 

의견/도움이 매우 도움이 될 것입니다.

+0

를 IMO는'date_trunc ('달', '에서 CreationDate ")'대신'to_char'를 사용하는 청소기입니다. 그렇지 않으면 정상적으로 보입니다. 쿼리에 대한'EXPLAIN' 결과는 무엇입니까? –

+0

매달 또는 총 ID에서 고유 ID를 계산 하시겠습니까? –

+0

감사합니다. Clodoaldo가 내 질문에 대답했다. 예, 별개의 ID를 계산하려고했습니다. 나는 앞으로 date_trunc를 사용해야합니다! :) – christinang89

답변

1

는 별개의 사용자를 계산하려면 :

select to_char(month, 'YYYY-MM') as "Month", count(*) 
from 
    generate_series(
     '2014-01-01'::date, current_date, '1 month' 
    ) monthseries (month) 
    left join (
     (
      select distinct date_trunc('month', "creationDate") as month, id 
      from action_a 
     ) a 
     full outer join (
      select distinct date_trunc('month', "creationDate") as month, id 
      from action_b 
     ) b using (month, id) 
    ) s using (month) 
group by 1 
order by 1 
+0

고마워요! 약간의 문법 오류가 있습니다. "... on (month, id) 사용"은 "on"이 필요하지 않습니다 :) – christinang89

+0

@ christinang89 물론, 수정되었습니다. –

관련 문제