简体   繁体   English

如何在 Postgres 的时间范围内获得平均值?

[英]How to get an average value in a timescale in Postgres?

I have a lot of values in a postgres db that include a time value.我在 postgres 数据库中有很多包含时间值的值。

The database contains a record unit colors, something like this:该数据库包含一个记录单元 colors,如下所示:

[
{
  id: 1234,
  unit: 2,
  color: "red",
  time: "Wed, 16 Dec 2020 21:45:30"
},
{
  id: 1235,
  unit: 2,
  color: "red",
  time: "Wed, 16 Dec 2020 21:47:30"
},{
  id: 1236,
  unit: 6,
  color: "blue",
  time: "Wed, 16 Dec 2020 21:48:30"
},
{
  id: 1237,
  unit: 6,
  color: "green",
  time: "Wed, 16 Dec 2020 21:49:30"
},
{
  id: 1237,
  unit: 6,
  color: "blue",
  time: "Wed, 16 Dec 2020 21:49:37"
},
]

I want to be able to query this list but in 10 minute averages, which should return the earliest record which contains the average.我希望能够以 10 分钟的平均值查询此列表,这应该返回包含平均值的最早记录。

For example in the 10 minute period of 21:40 - 21:50 I should only recieve the 2 unique units with the average value that they had within that time period.例如,在 21:40 - 21:50 的 10 分钟期间,我应该只收到 2 个具有该时间段内平均值的唯一单位。

The returned data should look something like this:返回的数据应如下所示:

[
{
  id: 1234,
  unit: 2,
  color: "red",
  time: "Wed, 16 Dec 2020 21:45:30"
},
{
  id: 1236,
  unit: 6,
  color: "blue",
  time: "Wed, 16 Dec 2020 21:48:30"
},
]

What type of query should I be using to acheive soething like this?我应该使用什么类型的查询来实现这样的目标?

Thanks谢谢

You can use distinct on :您可以使用distinct on

select distinct on (x.time_trunc, t.unit) t.*
from mytable t
cross join lateral (values (
    date_trunc('hour', time) 
        + extract(minute from time) / 10 * '10 minute'::interval)
) as x(time_trunc)
order by x.time_trunc, t.unit, t.time 

The trick is to truncate the timestamps to 10 minute.诀窍是将时间戳截断为 10 分钟。 For this, we use date arithmetics;为此,我们使用日期算术; I moved the computation in a lateral join so there is no need to repeat the expression.我在横向连接中移动了计算,因此无需重复表达式。 Then, distinct on comes into play, to select the earlier record per timestamp bucket and per unit.然后, distinct on开始发挥作用,select 每个时间戳桶和每个单元的较早记录。

I don't see how the question relates to an average whatsoever.我看不出这个问题与平均值有何关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM