I have 3 dates:
2016-08-17 12:29:01
2016-08-17 12:34:13
2016-08-17 12:39:26
And I would like to get the average time between them. If there are more than 60 seconds, then in minutes, and the same for hours.
I have 3 dates:
2016-08-17 12:29:01
2016-08-17 12:34:13
2016-08-17 12:39:26
And I would like to get the average time between them. If there are more than 60 seconds, then in minutes, and the same for hours.
A solution using window functions
follows:
SELECT
cadastro.data AS data,
EXTRACT(EPOCH FROM cadastro.data) - lag(EXTRACT( EPOCH FROM cadastro.data)) OVER (order by cadastro.data) AS intervalo
FROM
( SELECT unnest( ARRAY[ '2016-08-17 12:29:01'::timestamp, '2016-08-17 12:34:13'::timestamp, '2016-08-17 12:39:26'::timestamp ] ) as data) as cadastro
Output:
'2016-08-17 12:29:01';<NULL>
'2016-08-17 12:34:13';312
'2016-08-17 12:39:26';313
Reference:
Subtract the smallest date from the largest and divide by the row count - 1:
with cadastro (data) as ( values
('2016-08-17 12:29:01'::timestamp),
('2016-08-17 12:34:13'),
('2016-08-17 12:39:26')
)
select (max(data) - min(data)) / (count(*) - 1) as média
from cadastro
;
média
------------
00:05:12.5
The result is of type intervalo