按时间戳分钟查询postgres

时间:2017-12-17 13:09:07

标签: sql postgresql postgresql-9.3 postgresql-9.4

我想知道如何通过查询进行分组,我需要在数据库中对同一分钟的所有数据进行分组以对所有数据进行求和。

ws_controller_hist=>  SELECT timestamp, type, medium from default_dataset where type like 'status_devices' and timestamp> current_timestamp - interval '60 minutes' and organization_id = '9fc02db4-c3df-4890-93ac-8dd575ca5638' order by timestamp asc;

       timestamp        |      type      | medium
------------------------+----------------+--------
 2017-12-17 12:44:00+00 | status_devices | {1,0}
 2017-12-17 12:44:00+00 | status_devices | {1,0}
 2017-12-17 12:44:00+00 | status_devices | {1,0}
 2017-12-17 12:44:01+00 | status_devices | {1,0}
 2017-12-17 12:44:01+00 | status_devices | {1,0}
 2017-12-17 12:44:10+00 | status_devices | {0,1}
 2017-12-17 12:44:10+00 | status_devices | {0,1}

执行此查询

ws_controller_hist=>  SELECT timestamp, type, sum(medium[1]) from default_dataset where type like 'status_devices' and timestamp> current_timestamp - interval '60 minutes' and organization_id = '9fc02db4-c3df-4890-93ac-8dd575ca5638' group by timestamp, type order by timestamp asc;

       timestamp        |      type      | sum
------------------------+----------------+-----
 2017-12-17 12:44:00+00 | status_devices |   3
 2017-12-17 12:44:01+00 | status_devices |   2
 2017-12-17 12:44:10+00 | status_devices |   0

我想得到5分,这是分钟44中的总数可以理解吗?

1 个答案:

答案 0 :(得分:1)

我想你想要date_trunc()

select date_trunc('minute', timestamp) as timestamp_min, type, 
       sum(medium[1])
from default_dataset
where type like 'status_devices' and
      timestamp > current_timestamp - interval '60 minutes' and
      organization_id = '9fc02db4-c3df-4890-93ac-8dd575ca5638'
group by timestamp_min, type
order by timestamp_min asc;
相关问题