我使用的是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 |
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;
答案 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;