我目前正在使用这个:
select avg(tank_level)
from (
select row_number() over (order by id) as rn, tank_level
from data_tanksensor
where sensors_on_site_id = 91
) s
group by (rn + ((Select count(*)/10 From data_tanksensor where sensors_on_site_id = 91)-1))/ (Select count(*)/10 From data_tanksensor where sensors_on_site_id = 91)
;
从表中获得10个平均值。此表还有时间戳,我想获得10个平均tank_level中每个的平均时间戳。这用于创建历史图表。如果有人可以帮我修改此查询,也可以获得非常感谢的平均时间戳。提前谢谢。
表格如下所示
. id sensors_on_site_id tank_level timestamps
[PK] bigint integer double precision time without time zone
........... .................. ................ ......................
12345 91 7.5 2017-03-24 11:16:31.143362
12346 91 7.6 2017-03-24 11:21:31.148639
12347 91 5.4 2017-03-24 11:26:31.155739
12348 91 3.6 2017-03-24 11:31:31.156478
12349 91 8.5 2017-03-24 11:36:31.157303
12350 91 4.2 2017-03-24 11:41:31.172008
例如,如果我只想从中得到平均值,那么我的原始查询将是
select avg(tank_level)
from (
select row_number() over (order by id) as rn, tank_level
from data_tanksensor
where sensors_on_site_id = 91
) s
group by (rn + ((Select count(*)/2 From data_tanksensor where sensors_on_site_id = 91)-1))/ (Select count(*)/2 From data_tanksensor where sensors_on_site_id = 91)
;
粗略的查询缺少可以平衡时间戳的部分,这是我想要弄清楚的。但是我试图获得的预期结果将是
avg timestamp
double precision timestamp without time zone
................ ...........................
6.833333 2017-03-24 11:21:31...
5.433333 2017-03-24 11:36:31...
同样,这只是样本数据,平均每行数百个。感谢
答案 0 :(得分:1)
您可以将时间戳转换为unix时间戳,将值相加,除以值的数量并转换回时间戳。一个快速工作的例子:
with
__ts as(
select unnest(array[
'2015-11-22 09:31:00', '2015-11-22 09:32:00', '2015-11-23 11:31:00', '2015-11-23 11:32:00',
'2015-11-23 11:34:00', '2015-11-23 15:28:00', '2015-11-23 15:29:00', '2015-11-24 10:49:00',
'2015-11-24 10:50:00', '2015-11-24 11:18:00'
]::timestamp without time zone[]) as ts
)
select
to_timestamp(sum(extract(epoch from ts)) / (select count(1) from __ts))
from
__ts
答案 1 :(得分:0)
select to_timestamp(avg(timestamps)) "timestamps", avg(tank_level) "TankLevel"
from (
select row_number() over (order by id) as rn, tank_level, extract(epoch from timestamps) "timestamps"
from data_tanksensor
where sensors_on_site_id = 91
) s
group by (rn + ((Select count(*)/10 From data_tanksensor where sensors_on_site_id = 91)-1))/ (Select count(*)/10 From data_tanksensor where sensors_on_site_id = 91)
order by timestamps asc
;
弄清楚了
谢谢大家的例子