在我的PostgreSQL数据库中,我具有以下架构:
CREATE TABLE programs (
id integer,
description text
);
CREATE TABLE public.messages (
id integer,
program_id integer,
text text,
created_at timestamp with time zone
);
INSERT INTO programs VALUES(1, 'Test program');
INSERT INTO messages VALUES(1,1, 'Test message 1', now() - interval '7 days');
INSERT INTO messages VALUES(2,1, 'Test message 2', now() - interval '4 days');
INSERT INTO messages VALUES(3,1, 'Test message 3', now() - interval '1 days');
我想计算消息表中created_at
之间的间隔。它应该这样工作:
created_at
之间的间隔。created_at
之间的间隔。在PostgreSQL中可以做这种事情吗?
答案 0 :(得分:1)
如果您希望获得消息之间的平均时间,则无需获取连续的差异。只需查看最旧和最新的消息即可:
select program_id,
(max(created_at) - min(created_at)) / nullif(count(*) - 1, 0)
from messages
group by program_id;
答案 1 :(得分:1)
使用LAG
和窗口化的AVG
来获取差异和平均差距:
WITH cte AS (
SELECT *,
created_at-LAG(created_at) OVER(PARTITION BY program_id ORDER BY created_at) gap
FROM messages
)
SELECT *, AVG(gap) OVER(PARTITION BY program_id) AS avg_gap
FROM cte;