【问题标题】:Join on generate_series and count加入 generate_series 并计数
【发布时间】:2023-04-11 11:46:01
【问题描述】:

我正在尝试查找每月执行操作 A 或操作 B 的 # 个用户。

表:用户 - ID - “创作日期”

表:action_A - user_id (= user.id) - “创作日期”

表:action_B - user_id (= user.id) - “创作日期”

我试图做的一般想法是,我会找到在 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"

任何 cmets/ 帮助都会非常有帮助!

【问题讨论】:

  • IMO 使用 date_trunc('month', "creationDate") 而不是 to_char 更简洁。否则看起来很理智。 EXPLAIN 的查询输出是什么?
  • 您想统计每个月的不同 id 还是总 id?
  • 谢谢! Clodoaldo 回答了我的问题,是的,我正在尝试计算不同的 id :) 我会确保将来使用 date_trunc! :)

标签: postgresql join aggregate-functions postgresql-9.3 generate-series


【解决方案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

【讨论】:

  • 谢谢!有一个轻微的语法错误“...b on using (month, id)”“on”不是必需的:)
猜你喜欢
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 2020-11-19
相关资源
最近更新 更多