Postgres时间戳之间的时差,以分钟为单位

时间:2019-12-25 08:28:56

标签: postgresql datetime lag

我需要计算日期时间行之间的时间差。但是我想每天计算它们,也想将它们与id分组。我怎样才能做到这一点?我的桌子是这样的:enter image description here

2 个答案:

答案 0 :(得分:1)

麻烦之处在于模糊的术语“与时间戳的细微差别”。当Postgres执行时间戳减去时,结果是一个间隔。但是间隔由天,小时,分钟和秒组成。当您说细微差别时,您的意思是从间隔中提取细微差别。还是用(24 * 60 * days)+(60 * hours)+(minuets)表示总分钟数?请参见以下示例:

with test_dates(d1,d2) as
     ( values ('2019-10-02 11:00:47'::timestamp, '2019-10-02 07:35:02'::timestamp)
            , ('2015_09-15 11:15:42'::timestamp, '2019-10-22 17:45:00'::timestamp)
     ) 
select greatest(d1,d2) - least(d1,d2) int_diff
     , extract('minutes' from greatest(d1,d2) - least(d1,d2)) min_diff 
     , 60* (extract('hours' from greatest(d1,d2) - least(d1,d2))) +
       extract('minutes' from greatest(d1,d2) - least(d1,d2)) diff_hr_min
     , (24*60)*(extract('days' from greatest(d1,d2) - least(d1,d2))) +
       60* (extract('hours' from greatest(d1,d2) - least(d1,d2))) +
       extract('minutes' from greatest(d1,d2) - least(d1,d2))  diff_daya_hr_min          
from test_dates; 

答案 1 :(得分:0)

尝试一下:

SELECT DATE_PART('minute', max(date) - min(date)) AS time_difference 
FROM tablename 
GROUP BY DATE(date), id;

您可以将idDATE(date)添加到SELECT来检查结果是否正确,例如:

SELECT DATE(date), id, DATE_PART('minute', max(date) - min(date)) AS time_difference 
FROM tablename 
GROUP BY DATE(date), id;

有关更多信息,请参见Postgresql extracting functionsDate/Time functions