简体   繁体   中英

Postgres: Grouping an average from timestamps

I am having some issues trying to create an PostgreSQL query that does the following:

  • Take the duration in seconds from start and stop times
  • Specify the start/end (or greater than start), ignoring the rest
  • Group them against a list of colours
  • Average the duration to the group

The data looks something like this:

|colour | start | stop |
|blue|2020-02-03 22:18:08.561+00|2020-02-03 22:18:09.674+00|
|blue|2020-02-03 22:18:37.902+00|2020-02-03 22:18:40.479+00|
|red|2020-02-03 22:18:41.121+00|2020-02-03 22:18:42.272+00|
|green|2020-02-03 22:18:41.113+00|2020-02-03 22:18:42.835+00|
|red|2020-02-03 22:18:41.105+00|2020-02-03 22:18:43.223+00|

So far, I've only got the duration in seconds using:

SELECT colour, start, stop, 
EXTRACT(EPOCH FROM (stop - start)) as durationSeconds
FROM public.colour_record

That's as far as I've gotten. Any help wouldn't be great appreciated.

I you want the average duration per color, you can use aggregation as follows:

select 
    colour, 
    avg(extract(epoch from (stop - start))) as avg_duration_seconds
from public.colour_record
group by colour

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