【问题标题】:averaging timestamp data giving error in postgres平均时间戳数据在 postgres 中给出错误
【发布时间】:2020-09-11 05:46:48
【问题描述】:

一段时间以来,我一直在努力寻找答案。让我尝试迭代问题。我有一个名为 myTable 的表:(注意:下表只是具有数千行的大表的一小部分)

timestamp_original            data
2020/05/24 15.30.31.620         0
2020/05/24 15.30.31.649         1
2020/05/24 15.30.31.658         2
2020/05/24 15.30.31.668         3
2020/05/24 15.30.31.688         4
2020/05/24 15.30.31.698         5
2020/05/24 15.30.31.708         6
2020/05/24 15.30.31.738         7
2020/05/24 15.30.31.748         8
2020/05/24 15.30.31.758         9
2020/05/24 15.30.31.768         10
2020/05/24 15.30.31.809         11
2020/05/24 15.30.31.810         12
2020/05/24 15.30.31.812         13
2020/05/24 15.30.31.838         14
2020/05/24 15.30.31.848         15

我的期望是获取每毫秒之间的数据平均值,同时将毫秒舍入到 10 秒。

timestamp_new                  myData
2020/05/24 15.30.31.6           2.5
2020/05/24 15.30.31.7           8
2020/05/24 15.30.31.8           13

我的代码如下:

SELECT date_trunc('milliseconds','timestamp_original')::timestamp(1) as timestamp_new, 
avg(data) as myData
FROM myTable
GROUP BY 1 ORDER BY timestamp_new;

但我得到的输出如下,这没有任何意义

timestamp_new                  myData
2020/05/24 15.30.31.6           0.5
2020/05/24 15.30.31.7           5
2020/05/24 15.30.31.8           12

请帮助我。

【问题讨论】:

  • 你错过了一个群组
  • 您的意思是将 avg(data) 添加到 group by 吗??

标签: sql postgresql time-series


【解决方案1】:

到timestamp(1) 的转换是舍入而不是截断。一个简单的解决方案是减去 50 毫秒:

SELECT date_trunc('millisecond', timestamp_original - interval '50 millisecond')::timestamp(1) as timestamp_new,
       avg(data) as myData
FROM myTable
GROUP BY 1
ORDER BY timestamp_new;

Here 是一个 dbfiddle。

【讨论】:

  • tbh 我不明白删除 50 毫秒的逻辑,但现在的输出符合要求。如果可能的话,您能否详细说明一下。非常感谢您的支持
  • @codeheadache 。 . .我以为我在问题中解释了这一点。转换 rounds 值,因此 1.6 变为 2(例如)。您希望它变为 1,因此减去一半。
猜你喜欢
  • 2020-11-06
  • 2018-11-18
  • 2013-12-22
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 2015-02-02
相关资源
最近更新 更多