计算日期范围内每种状态的计数

时间:2019-02-24 12:37:49

标签: sql postgresql

我使用的是PostgreSQL,我试图实现如何构建查询来计算范围内每个日期的事件每个状态的计数

我的事件表如下:


| dateStart  | dateEnd    | status |
|----------------------------------|
| 2019-02-10 | 2019-02-11 | Type1  |
| 2019-02-10 | 2019-02-16 | Type1  | 
| 2019-02-10 | 2019-02-12 | Type2  |
| 2019-02-11 | 2019-02-16 | Type1  |
| 2019-02-12 | 2019-02-14 | Type2  |
| 2019-02-13 | null       | Type2  |
| 2019-02-12 | 2019-02-13 | Type2  |
| 2019-02-15 | 2019-02-16 | Type3  |
| 2019-02-14 | 2019-02-14 | Type1  |

事件从dateStart开始并以dateEnd结尾(如果仍在进行中,则为null),并且如果dateStart-dateEnd以某种方式交叉查询日期范围,则必须将其计入范围内的每个日期。

我有一个日期范围,例如:

从:2019-02-12到:2019-02-15

实际上我想在该范围内得到这样的结果:

| date       | type1Count | type2Count | type3Count |
|---------------------------------------------------|
| 2019-02-12 | 2          | 3          | 0          | 
| 2019-02-13 | 2          | 3          | 0          | 
| 2019-02-14 | 3          | 2          | 0          | 
| 2019-02-15 | 2          | 1          | 1          |

这张照片演示了想法:

enter image option here

这就是我目前所拥有的,但是它仅使用dateStart

  SELECT DATE_TRUNC('day', "events"."dateStart") AS dateStart,
          COUNT(CASE WHEN "events"."status" = 'Type1' THEN 1 END) AS "Type1",
          COUNT(CASE WHEN "events"."status" = 'Type2' THEN 1 END) AS "Type2",
          COUNT(CASE WHEN "events"."status" = 'Type3' THEN 1 END) AS "Type3",
        FROM "events"
        GROUP BY 1
        ORDER BY 1;

我将不胜感激

1 个答案:

答案 0 :(得分:1)

最简单的方法是Postgres,用于generate_series()

select d.dte, count(e.type) as total,
       count(*) filter (where e.type = 'Type1') as type1_cnt,
       count(*) filter (where e.type = 'Type2') as type2_cnt,
       count(*) filter (where e.type = 'Type3') as type3_cnt
from (select generate_series(min(datestart), max(datestart), interval '1 day') as dte
      from events
     ) d left join
     events e
     on d.dte >= e.datestart and d.dte <= e.dateend
group by d.dte
order by d.dte;