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

时间:2015-03-31 14:38:13

标签: sql postgresql aggregate-functions

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

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

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

2 个答案:

答案 0 :(得分:1)

乍一看,你看起来像是在执行计数功能,而不是你需要的总和,你只需要计算两次记录。

sum( CASE WHEN (created_at >= date_trunc('day', now()) - interval '6d') 
       THEN 1 ELSE 0 END) AS ct,
sum(CASE WHEN (canceled_at >= date_trunc('day', now()) - interval '6d') 
       THEN 1 ELSE 0 END) AS dl  

你需要使用sum然后将所有情况添加到你返回1时的情况而不是计数,只计算所有值,无论它们是1还是0!

答案 1 :(得分: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;

CTE var仅为方便提供一次起始时间戳。

SQL Fiddle.