小编典典

获取上周的创建和删除条目

sql

通过此查询,我可以获取上周创建的所有条目:

SELECT day, COALESCE(ct, 0) AS ct
FROM  (SELECT now::date - d AS day FROM generate_series (0, 6) d) d  -- 6, not 7
  LEFT   JOIN (
     SELECT created_at::date AS day, count(*) AS ct 
     FROM   entries
     WHERE  created_at >= date_trunc('day', now()) - interval '6d'
     GROUP  BY 1
  ) e USING (day);

它返回这样的结果:

 count | date
   2   |  15.01.2014
   0   |  14.01.2014
   1   |  13.01.2014
   0   |  12.01.2014
   0   |  11.01.2014
   0   |  10.01.2014
   9   |  09.01.2014

现在,我还想显示上周所有已删除的条目!我可以通过实地了解他们deleted_at:我尝试过的是:

SELECT day, COALESCE(ct, 0) AS created, COALESCE(dl,0) AS deleted
FROM  (SELECT current_date - d AS day FROM generate_series (0, 6) d) d  
LEFT   JOIN (
   SELECT created_at::date AS day, 
      count(
        CASE WHEN (created_at >= date_trunc('day', now()) - interval '6d') THEN 1 ELSE 0 END
      ) AS ct,
count(
    CASE WHEN (canceled_at >= date_trunc('day', now()) - interval '6d') THEN 1 ELSE 0 END
) AS dl  
  FROM   entries

   GROUP  BY 1
  ) e USING (day);

但这没有用!现在,我得到两个相同的行:

deleted | created | date
  2     |  2      |  15.01.2014
  0     |  0      |  14.01.2014
  1     |  1      |  13.01.2014
  0     |  0      |  12.01.2014
  0     |  0      |  11.01.2014
  0     |  0      |  10.01.2014
  9     |  9      |  09.01.2014

我怎么了 如何显示已创建和已删除的条目?


阅读 196

收藏
2021-04-14

共1个答案

小编典典

由于两个时间戳在时间范围内可以存在0-n次并且彼此独立,因此您必须做更多的事情:

需要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;

CTEvar仅是为了方便地提供一次启动时间戳。

2021-04-14