我正在尝试找到每月执行操作A或操作B的#个用户。
表:用户 - ID - “creationDate”
表:action_A - user_id(= user.id) - “creationDate”
表:action_B - user_id(= user.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 :(得分: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