SQL 平均到达间隔时间、日期之间的时间
我有一个带有连续时间戳的表:
2011-03-17 10:31:19
2011-03-17 10:45:49
2011-03-17 10:47:49 ...
我需要找到每个(可能有几十个)之间的平均时间差(以秒为单位)或任何最简单的时间差,我可以从那里开始使用它。例如,上述仅前两次的到达间隔时间将为 870 (14m 30s)。对于所有三个时间,其结果为:(870 + 120)/2 = 445 (7m 25s)。
请注意,我使用的是 postgreSQL 8.1.22 。
编辑:我上面提到的表来自另一个查询,它实际上只是时间戳的一列列表
I have a table with sequential timestamps:
2011-03-17 10:31:19
2011-03-17 10:45:49
2011-03-17 10:47:49
...
I need to find the average time difference between each of these(there could be dozens) in seconds or whatever is easiest, I can work with it from there. So for example the above inter-arrival time for only the first two times would be 870 (14m 30s). For all three times it would be: (870 + 120)/2 = 445 (7m 25s).
A note, I am using postgreSQL 8.1.22 .
EDIT: The table I mention above is from a different query that is literally just a one-column list of timestamps
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定我完全理解你的问题,但这可能就是你正在寻找的:
内部查询计算每行与前一行之间的距离。结果是表中每行的间隔。
外部查询只是对所有差异进行平均。
Not sure I understood your question completely, but this might be what you are looking for:
The inner query calculates the distance between each row and the preceding row. The result is an interval for each row in the table.
The outer query simply does an average over all differences.
我想你想找到 avg(timestamptz)。
我的解决方案是 avg(当前 - 最小值)。但由于结果是区间,所以再次将其添加到最小值。
i think u want to find avg(timestamptz).
my solution is avg(current - min value). but since result is interval, so add it to min value again.
如果您无法升级到支持窗口函数的 PG 版本,您
可能会“以缓慢的方式”计算表的连续步骤。
假设您的表是“tbl”并且时间戳列是“ts”:
但不要这样做。它的表现将会很糟糕。请做什么
a_horse_with_no_name
建议,并且使用窗口函数。If you cannot upgrade to a version of PG that supports window functions, you
may compute your table's sequential steps "the slow way."
Assuming your table is "tbl" and your timestamp column is "ts":
But don't do that. Its performance will be terrible. Please do what
a_horse_with_no_name
suggests, and use window functions.