如何计算Postgresql的平均时间

时间:2018-04-17 14:18:39

标签: sql postgresql average

我正在尝试执行一个查询,这个查询会让我知道我的表格的结构如下:

RunnerID,   State,   Timestamp_race
R1          start     2017-04-11 12:15:15.722415
R2          start     2017-04-11 13:15:15.722415
R1          finish    2017-04-11 15:15:15.722415
R1          finish    2017-04-11 17:15:15.722415

跑步者在不同时间开始并在不同时间结束,想法是计算整个比赛的平均时间

2 个答案:

答案 0 :(得分:0)

您可以使用extract(epoch)获取每场比赛的秒数,然后取平均值:

select avg(seconds) as avg_seconds
from (select runnerid, extract(epoch from max(Timestamp_race) - min(Timestamp_race)) as seconds
      from t
      group by runnerid
     ) r;

这假设最小时间是开始,最大值是结束。

编辑:

如果您希望将平均值作为间隔,则可以执行以下操作:

select avg(diff) as avg_diff
from (select runnerid, (max(Timestamp_race) - min(Timestamp_race)) as diff
      from t
      group by runnerid
     ) r;

答案 1 :(得分:0)

这是一种更好的格式:

select to_char(avg(seconds),'DD HH24:MI:SS.MS') as avg_time
from (select runnerid, max(Timestamp_race) - min(Timestamp_race) as seconds
      from race t
      group by runnerid
     ) r;

|        avg_time |
|-----------------|
| 00 03:30:00.000 |