填补 PostgreSQL 上 SQL 查询中缺失的日期间隙

问题描述 投票:0回答:1

我有一张桌子

messages
,看起来像:

状态 创建于 更新于
已发送 时间戳 时间戳
排队 时间戳 时间戳
失败了 时间戳 时间戳

我想要一个以易于绘制图表的方式输出值的查询,我想出了这个查询:

SELECT date_trunc('hour', created_at) as hour_created, count(created_at), status 
FROM messages 
WHERE created_at >= current_timestamp - interval '1 day' 
GROUP BY (status, hour_created)

该查询输出以下内容:

小时_创建 状态
2021-10-11 08:00:00-04 10 已发送
2021-10-11 09:00:00-04 95 排队
2021-10-11 10:00:00-04 174 已发送
2021-10-11 12:00:00-04 1 已发送
2021-10-11 13:00:00-04 1 排队
2021-10-11 13:00:00-04 2 已发送
2021-10-11 14:00:00-04 1 已发送
2021-10-11 18:00:00-04 2 已发送

注意时间间隔,我想用所有可能的状态(排队、失败和发送)和零来填充这些间隔

sql postgresql datetime
1个回答
1
投票

您可以使用生成系列:

select date_trunc('hour', created_at) as hour_created
  , count(created_at)
  , status 
from generate_series(date_trunc('hour',current_timestamp) - interval '1 day' ,date_trunc('hour',current_timestamp), '1 hour') intervals (cdate)
cross join (select * from (values ('failed'),('queued'),('sent')) s (status)) statuses
join messages t
  on t.status = statuses.status
  and t.created_at = intervals.cdate
where created_at >= current_timestamp - interval '1 day' 
group by statuses.status, intervals.cdate
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.