sql - 如何将时间段划分为部分?

标签 sql postgresql

表中有一列存储记录创建的时间。查询指定结束日期和开始日期,然后将间隔分为 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/

相关文章:

sql - 从表中选择项目时在 postgres 中使用 'COUNT(*) OVER() AS'

sql - 在 postgres 中使用带有时间戳的条件语句时出错

sql - 如何在分组后获取所有 pk(查找重复项)

mysql - 写入sql文件

python - 使用 django-tastypie 创建、更新和删除调用

mysql - 如何查看未与当前用户进行事件游戏的所有用户

postgresql - 将 Postgresql 数据库从 SQL_ASCII 就地转换为 UTF8

mysql - SQL查询: Single row has multiple foreign keys from another table

postgresql - 插入整数列时不要静默舍入浮点输入

PostgreSQL 迁移和恢复