Get created as well as deleted entries of last week

后端 未结 2 518
星月不相逢
星月不相逢 2021-01-27 07:26

With this query I can get all entries created during the last week:

SELECT day, COALESCE(ct, 0) AS ct
FROM  (SELECT now::date - d AS day FROM generate_series (0,         


        
2条回答
  •  滥情空心
    2021-01-27 08:05

    Since both timestamps can exist 0 - n times in the time frame and independent from each other, you have to do more:

    Requires Postgres 9.3+:

    WITH var(ts_min) AS (SELECT date_trunc('day', now()) - interval '6 days')
    SELECT day
         , COALESCE(c.created, 0) AS created
         , COALESCE(d.deleted, 0) AS deleted
    FROM   var v
    CROSS  JOIN LATERAL (
       SELECT d::date AS day
       FROM   generate_series (v.ts_min
                             , v.ts_min + interval '6 days'
                             , interval '1 day') d
       ) t
    LEFT   JOIN (
       SELECT created_at::date AS day, count(*) AS created
       FROM   entries
       WHERE  created_at >= (SELECT ts_min FROM var)
       GROUP  BY 1
       ) c USING (day)
    LEFT   JOIN (
       SELECT canceled_at::date AS day, count(*) AS deleted
       FROM   entries
       WHERE  canceled_at >= (SELECT ts_min FROM var)
       GROUP  BY 1
       ) d USING (day)
    ORDER  BY 1;
    

    The CTE var is only for the convenience to provide the starting timestamp once.

    SQL Fiddle.

提交回复
热议问题