如何使用 SQL 计算多天的每小时平均值

How to average hourly values over multiple days with SQL

我有一个 SQL table (postgreSQL/TimescaleDB) 每小时值,例如:

Timestamp               Value
...
2021-02-17 13:00:00     2
2021-02-17 14:00:00     4
...
2021-02-18 13:00:00     3
2021-02-18 14:00:00     3
...

我想获取特定时间跨度内映射到今天日期的每小时的平均值,所以类似这样:

select avg(value)
from table
where Timestamp between '2021-02-10' and '2021-02-20'
group by *hourpart of timestamp*

今天 (2021-10-08) 的结果应该是:

...
Timestamp               Value
2021-10-08 13:00:00     2.5
2021-10-08 14:00:00     3.5
...

如果我明天 (2021-10-09) 也这样做 select 结果应更改为:

...
Timestamp               Value
2021-10-09 13:00:00     2.5
2021-10-09 14:00:00     3.5
...

你必须这样写你的查询:

select avg(value)
from table
where Timestamp between '2021-02-10' and '2021-02-20'
group by substring(TimeStamp,1,10), substring(TimeStamp,11,9)

我自己解决了这个问题: 解决方案:

SELECT EXTRACT(HOUR FROM table."Timestamp") as hour,
avg(table."Value") as average
from table
where Timestamp between '2021-02-10' and '2021-02-20'
group by hour
order by hour;