在generate_series上加入并计数



我正试图找到每月执行操作A或操作B的#用户。

表:用户-id-"creationDate"

表:action_A-user_id(=user.id)-"creationDate"

表:动作_B-user_id(=user.id)-"creationDate"

我试图做的总体想法是,我会找到在X月执行操作A的用户列表和在X月进行操作B的用户列表,然后根据每月日期的generate_se系列计算每个月有多少ID。

然而,我尝试了以下操作,查询在运行时超时,我不确定是否有任何方法可以优化它(或者它是否正确)。

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"

任何意见/帮助都将非常有帮助!

如果您想计算不同的用户:

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

相关内容

  • 没有找到相关文章

最新更新