如何将当前的部分月份与之前的部分月份与postgres进行比较?

时间:2017-06-23 18:31:18

标签: sql postgresql reporting

我正在构建一些基本报告,我想看看我是否有望超越上个月的指标而不等待月份结束。基本上我想比较6月1日(当月开始)到6月23日(current_date)与5月1日(上月初)到5月23日(current_date - 1个月)。

我的目标是显示执行event1和event2的不同用户的数量。

这是我到目前为止所拥有的:

CREATE VIEW events AS
  (SELECT *
   FROM public.event
   WHERE TYPE in ('event1',
                  'event2')
     AND created_at > now() - interval '1 months' );


CREATE VIEW MAU AS
  (SELECT EXTRACT(DOW
                  FROM created_at) AS month,
          DATE_TRUNC('week', created_at) AS week,
          COUNT(*) AS total_engagement,
          COUNT(DISTINCT user_id) AS total_users
   FROM events
   GROUP BY 2,
            1
   ORDER BY week DESC);

SELECT month,
       week,
       SUM(total_engagement) OVER (PARTITION BY month
                                   ORDER BY week) AS total_engagment
FROM MAU
ORDER BY 1 DESC,
         2

以下是返回内容的示例:

Month  Week                 Unique Engagement
6      2017-05-22 00:00:00  165
6      2017-05-29 00:00:00  355
6      2017-06-05 00:00:00  572
6      2017-06-12 00:00:00  723
5      2017-05-22 00:00:00  757
5      2017-05-29 00:00:00  1549
5      2017-06-05 00:00:00  2394
5      2017-06-12 00:00:00  3261
5      2017-06-19 00:00:00  3592

预期回报

Month  Day  Total Engagement
6      1     50
6      2     100
6      3     180
5      1     89
5      2     213
5      3     284
5      4     341

你能指出我错在哪里或者有更简单的方法吗?

1 个答案:

答案 0 :(得分:2)

您在问题中的日期,周数和月份令人困惑,但是根据预期的输出,我假设您需要月份编号,一个月内的周数以及这些对的计数。

SELECT 
  month,
  week,
  count(*) as total_engagement
FROM (
  SELECT
    extract(month from created_at) as month,
    extract('day' from date_trunc('week', created_at::date) -
                   date_trunc('week', date_trunc('month', created_at::date))) / 7 + 1 as week
  FROM public.event
  WHERE type IN ('event1', 'event2')
    AND created_at > now() - interval '1 month'
  ) t
GROUP BY 1,2

最有趣的部分可能是在一个月内获得周数,为此您可以查看this answer