我有以下查询:
WITH t as ( SELECT date_trunc('hour', time_series) as trunc FROM generate_series('2013-02-27 22:00'::timestamp, '2013-02-28 2:00', '1 hour') as time_series GROUP BY trunc ORDER BY trunc ) SELECT DISTINCT ON(trunc) trunc, id FROM t LEFT JOIN ( SELECT id, created, date_trunc('hour', created) as trunc_u FROM event ORDER BY created DESC ) u ON trunc = trunc_u
结果如下:
"2013-02-27 22:00:00"; "2013-02-27 23:00:00";2 "2013-02-28 00:00:00";5 "2013-02-28 01:00:00"; "2013-02-28 02:00:00";
表格event具有id,created以及其他一些列,但此处仅与之相关。上面的查询为我提供了id在给定trunc时间段内生成的最后一个事件(由于DISTINCT ON每个周期都得到了很好的汇总)。
event
id
created
trunc
DISTINCT ON
现在,NULL如果在给定的时间段内未发生任何事件,此查询将产生。我希望它返回以前的可用时间id,即使它来自不同的时间段。IE:
NULL
"2013-02-27 22:00:00";0 "2013-02-27 23:00:00";2 "2013-02-28 00:00:00";5 "2013-02-28 01:00:00";5 "2013-02-28 02:00:00";5
我确信我缺少一些简单的方法来完成此任务。有什么建议吗?
尝试:
WITH t as ( SELECT time_series as trunc FROM generate_series('2013-02-27 22:00'::timestamp, '2013-02-28 2:00', '1 hour') as time_series ) SELECT DISTINCT ON(t.trunc) t.trunc, e.id FROM t JOIN event e ON e.created < t.trunc ORDER BY t.trunc, e.created DESC
如果太慢-告诉我。我会给你一个更快的查询。