Postgres:计算连续值之间的时间间隔(以秒为单位)
我想知道我们如何计算连续日期时间的差异(例如以天或秒为单位),考虑下面的示例表:
time value
2020-03-30 00:25:10 10112
2020-04-02 08:04:03 45665
2020-04-10 09:55:56 112
2020-04-10 13:12:00 858
2020-04-28 10:15:59 89965
2020-05-30 22:31:02 12
这是由 pandas' diff()
:
0 NaT
1 3 days 07:38:53
2 8 days 01:51:53
3 0 days 03:16:04
4 17 days 21:03:59
5 32 days 12:15:03
换句话说,Postgres相当于pandas' diff()
?
I was wondering how we can compute the difference of successive date-times (for example in days or seconds), considering the sample table below:
time value
2020-03-30 00:25:10 10112
2020-04-02 08:04:03 45665
2020-04-10 09:55:56 112
2020-04-10 13:12:00 858
2020-04-28 10:15:59 89965
2020-05-30 22:31:02 12
Here is a desired result generated by pandas' diff()
:
0 NaT
1 3 days 07:38:53
2 8 days 01:51:53
3 0 days 03:16:04
4 17 days 21:03:59
5 32 days 12:15:03
In other words, what is the Postgres equivalent to pandas' diff()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地减去滞后时间戳,然后使用
to_char
。例如:输出:
db-fiddle 上的演示
注意 如果您还想要行号,则可以添加一个,因为
您还可以使用
EXTRACT
:输出
db-fiddle 演示
You can simply subtract a lagged timestamp, and then output as an interval or in the format you desire using
to_char
. For example:Output:
Demo on db-fiddle
Note if you want a row number as well, you can add one as
You can also get the value in seconds using
EXTRACT
:Output
Demo on db-fiddle
row_number
对结果行进行计数,而lag
则按定义的顺序获取上一行的值。row_number
counts the result rows, andlag
gets you the value from the previous row in the defined order.