PostgreSQL format lag column
-
14-11-2019 - |
Pregunta
This query works great for finding the difference between successive rows:
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;
...but the results come out like:
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
What would be really groovy is if I could format that diff column to just seconds and millis (e.g. 2.54502). I tried using date_trunc() and extract(), but I can't seem to get the syntax right.
Solución
The result of created_at - lag(create_at) is a value of type interval
.
You can get the seconds of an interval
using extract(epoch from interval_value)
So in your case it would be:
extract(epoch from (created_at - lag(created_at, 1)) )
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow