简体   繁体   中英

PostgreSQL Average Timestamp Difference (by Group)

Assume I have a table with a timestamp column, timestamp, and a grouping column, foo.

eg

CREATE TABLE my_table (
    id        SERIAL PRIMARY KEY,
    foo       integer NOT NULL,
    timestamp timestamp without time zone NOT NULL
);

What I would like to do is get the average time difference in each group ( GROUP BY foo ) and then get the average of those averages.

The only thing I could come across is getting just the average of all the rows (ungrouped):

SELECT avg(difference)
FROM ( 
  SELECT timestamp - lag(timestamp) OVER (ORDER BY timestamp) as difference
  FROM my_table
) t;

I am running PostgreSQL 9.6.11

SELECT avg(avg_diff) from (
  SELECT foo, avg(difference) as avg_diff
  FROM ( 
    SELECT timestamp - lag(timestamp) OVER (ORDER BY timestamp) as difference
    FROM my_table
  ) t
  group by foo
) t1;

The simplest way is simple arithmetic:

select (max(timestamp) - min(timestamp)) / (count(*) - 1)
from t;

That is, the average duration between the timestamps is the maximum minus the minimum divided by one less than the total number of timestamps.

Note: This assumes that the timestamps are either increasing or decreasing -- which is quite typical for this type of problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM