我有下表:
Reservations
| id | status | created_at |
| 1 | Opened | 2019-11-12 11:46:11 |
| 1 | Completed | 2019-11-19 23:03:24 |
| 1 | Pending | 2019-11-15 12:04:13 |
| 2 | Opened | 2019-11-14 11:46:11 |
| 2 | Completed | 2019-11-20 23:03:24 |
| 2 | Pending | 2019-11-17 12:04:13 |
我也有一张桌子,每个日历日从2019-11-01到2019-12-31。
我需要找出在上述时间段内每个日历日存在每种状态的次数。
如果状态在2019-12-14为打开,在2019-12-17为待处理,我需要计算一下从2019-12开始每天的状态为打开- 14至2019-12-17。
理想:
|2019-11-12 00:00:00 | Opened | 1 |
|2019-11-12 00:00:00 | Pending | 0 |
|2019-11-12 00:00:00 | Completed | 0 |
|2019-11-13 00:00:00 | Opened | 1 |
|2019-11-13 00:00:00 | Pending | 0 |
|2019-11-13 00:00:00 | Completed | 0 |
|2019-11-14 00:00:00 | Opened | 2 |
|2019-11-14 00:00:00 | Pending | 0 |
|2019-11-14 00:00:00 | Completed | 0 |
|2019-11-15 00:00:00 | Opened | 1 |
|2019-11-15 00:00:00 | Pending | 1 |
|2019-11-15 00:00:00 | Completed | 0 |
非常感谢您的帮助。
我会这样:获取每个ID的每个状态的开始和结束,使用表格在2019年11月1日至2019年12月31日之间的每个日历日计算发生次数,并按状态和日期进行基本计数
with Reservations cte as
(
select
a.id, a.status, a.created_at::date,
LAG(a.created_at::date, 1,0) OVER (PARTITION BY YEAR(a.id) ORDER BY YEAR(a.created_at))
AS Ended_at
Reservations a
)
Select b.day, status, count(*)
from Reservations a inner join calendar b on b.day >= created_at and
b.day < Ended_at
group by b.day, status