如何在指定的时间范围内检查每小时是否有记录然后计算?

时间:2017-11-30 15:52:01

标签: postgresql

我正在使用PostgreSQL,这是我的表measurement_archive

+-----------+------------------------+------+-------+
| sensor_id | time                   | type | value |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 01:53:11+00 | PM25 | 34.32 |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 02:15:11+00 | PM25 | 32.1  |
+-----------+------------------------+------+-------+
| 123       | 2017-11-26 04:32:11+00 | PM25 | 75.3  |
+-----------+------------------------+------+-------+

我需要一个查询来记录指定的时间范围(例如2017-01-01 00:00:00到2017-12-01 23:59:59),然后检查是否每小时都有至少1条记录 - 如果有,则将结果加1。

所以,如果我在2017-11-26 01:00:00到2017-11-26 04:59:59 + 00上面对sensor_id == 123进行上述查询那么结果应该是3

2 个答案:

答案 0 :(得分:1)

select count(*)
from (
    select date_trunc('hour', time) as time
    from measurement_archive
    where
        time >= '2017-11-26 01:00:00' and time < '2017-11-26 05:00:00'
        and
        sensor_id = 123
    group by 1
) s

答案 1 :(得分:0)

替代解决方案将使用distinct,

{{1}}