表中有一列存储记录创建的时间。查询指定结束日期和开始日期,然后将间隔分为 n 个部分。在每个间隙中,我需要计算数据库中的记录数。 告诉我要添加到查询中的内容。另外,我需要计算记录的数量,即使它们当时不是。
F.E.
----------------------------
id | query date |
----------------------------
1 | 2017-06-08 01:23:00 |
2 | 2017-06-08 01:24:19 |
3 | 2017-06-08 01:24:21 |
4 | 2017-06-08 01:24:36 |
5 | 2017-06-08 01:24:37 |
6 | 2017-06-08 01:24:41 |
----------------------------
我选择从 2017-06-08 01:24:00 到 2017-06-08 01:26:00 的时间段,并将这个时间段分成 4 个部分,然后等待
------------------------------
count | query date |
------------------------------
2 | 2017-06-08 01:24:00 |
3 | 2017-06-08 01:24:30 |
0 | 2017-06-08 01:25:00 |
0 | 2017-06-08 01:25:30 |
------------------------------
我的开始
select to_timestamp(extract(epoch from query_date)/extract(epoch FROM age('2017-06-08 01:25:00', '2017-06-08 01:24:00'))/60), count(*) from logs group by extract(epoch from query_date)/extract(epoch FROM age('2017-06-08 01:25:00', '2017-06-08 01:24:00'))/60;
最佳答案
尝试generate_series
,类似:
t=# with a as (
with ali as (
select g from generate_series('2017-06-08 01:24:00','2017-06-08 01:26:00','30 seconds'::interval) g
)
select g as t1, lead(g) over (order by g) t2
from ali
limit 4
)
select count(id), a.t1, coalesce(avg(id),0)
from a
left outer join logs l on l.query_date >= t1 and l.query_date <t2
group by a.t1
order by t1;
count | t1 | coalesce
-------+------------------------+--------------------
2 | 2017-06-08 01:24:00+00 | 2.5000000000000000
3 | 2017-06-08 01:24:30+00 | 5.0000000000000000
0 | 2017-06-08 01:25:00+00 | 0
0 | 2017-06-08 01:25:30+00 | 0
(4 rows)
已更新以与 OP 通知协调 - 我使用 coalesce 为 avg()
返回 NULL
关于sql - 如何将时间段划分为部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44430987/