PostgreSQL格式滞后列

时间:2012-02-28 18:31:52

标签: postgresql lag

此查询非常适合查找连续行之间的差异:

select id, created_at, created_at - lag(created_at, 1) 
over (order by created_at) as diff
from fistbumps where bumper_id = 2543 
and created_at between '2012-01-11' and '2012-01-12' order by created_at;

......但结果如下:

   id   |         created_at         |      diff       
--------+----------------------------+-----------------
 197230 | 2012-01-11 00:04:31.774426 | 
 197231 | 2012-01-11 00:04:32.279181 | 00:00:00.504755
 197232 | 2012-01-11 00:04:33.961665 | 00:00:01.682484
 197233 | 2012-01-11 00:04:36.506685 | 00:00:02.54502

如果我可以将diff列格式化为秒和毫秒(例如2.54502),那么真正很常见的是。我尝试使用date_trunc()和extract(),但我似乎无法正确使用语法。

1 个答案:

答案 0 :(得分:3)

created_at - lag(created_at)的结果是类型interval的值。

您可以使用interval

获取extract(epoch from interval_value)的秒数

所以在你的情况下,它将是:

extract(epoch from (created_at - lag(created_at, 1)) )