【问题标题】:PostgreSQL query for intervals of 1 min with accumulated sum over all the timeframe [duplicate]PostgreSQL查询间隔为1分钟,在所有时间范围内累积总和[重复]
【发布时间】:2013-08-23 01:57:00
【问题描述】:

到目前为止,我一直在努力处理这个查询,我可以创建 1 分钟的间隔,但是我需要的两列的总和只给出了那个分钟,而不是随时间累积的总和

SELECT
    TIMESTAMP WITH TIME ZONE 'epoch' +
    INTERVAL '1 second' * round(extract('epoch' from "Timestamp") / 60) * 60 as Timestamp",
    SUM("Particles"), sum("Bio")
from "Results" 
where "SampleID" = 50 
GROUP BY round(extract('epoch' from "Timestamp") / 60)
ORDER BY "Timestamp" DESC

这是我正在使用的查询,结果是这些

          Timestamp      |Sum |Sum
"2013-08-09 14:17:00-07" | 61 | 4
"2013-08-09 14:16:00-07" | 64 | 6
"2013-08-09 14:15:00-07" | 29 | 5
"2013-08-09 14:14:00-07" | 96 | 1
"2013-08-09 14:13:00-07" | 43 | 2

但我需要最后两列的累计和

Select
    TIMESTAMP WITH TIME ZONE 'epoch' +
    INTERVAL '1 second' * round(extract('epoch' from "Timestamp") / 60) * 60 as "Timestamp",
    sum("Particles") over (order by "Timestamp") as Cumulative_Part, 
    sum("Bio") over (order by "Timestamp") as Cumulative_Bio from "Results" 
where
    "SampleID" = 50 and
    "Timestamp" between '2013-08-09 14:13:00' and '2013-08-09 14:17:00'
GROUP BY round(extract('epoch' from "Timestamp") / 60)
Order by "Timestamp" DESC

【问题讨论】:

  • 是的,它可以工作,我只需要稍微改变一下,谢谢!!

标签: sql database postgresql group-by


【解决方案1】:

如果你有 postgresql 8.4 或更高版本,你可以使用OVER(ORDER BY..) 构造

SELECT...
, SUM("Particles") OVER(ORDER BY TimeStamp_Field) as SUM_Particles
...

查看here了解更多信息

【讨论】:

  • 我收到一条错误消息,提示“列“Results.Particles”必须出现在 GROUP BY 子句中或用于聚合函数中”
  • 请将新的完整 SQL 语句添加到您的原始问题中。仅从您的评论很难判断发生了什么。
  • 我知道问题与我获取间隔的方式有关,因为我在没有得到间隔的情况下尝试您的答案并且工作正常,但我需要以 1 分钟的间隔分隔时间戳跨度>
猜你喜欢
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 2020-03-12
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多