2012-02-28 53 views
0

這個查詢尋找連續行之間的差別的偉大工程:PostgreSQL的格式後柱

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 

什麼是真正的常規是,如果我可以將該差異列格式化爲秒和毫秒(例如2.54502)。我嘗試使用date_trunc()和extract(),但我似乎無法得到正確的語法。

回答

3

created_at - lag(create_at)的結果是interval類型的值。

可以使用extract(epoch from interval_value)

所以你的情況這將是得到一個interval的秒:

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

它返回秒,不毫秒。 – Eelke 2012-02-28 19:08:59

+0

@Eelke:謝謝,糾正。 – 2012-02-28 19:13:15