I have a table where the same ID can have multiple entries with start time and end time. How would I calculate the total time spent by the ID. The result I would want for the table below would be 11 minutes.
ID | start time | end time |
---|---|---|
123 | 5:30:00 | 5:35:00 |
123 | 5:36:00 | 5:40:00 |
123 | 5:36:00 | 5:40:00 |
123 | 5:36:00 | 5:39:00 |
123 | 5:38:00 | 5:42:00 |
I tried a few things but I was only able to take care of the cases where the start times were the same, not overlapping.
3
Answers
Assuming that the start and stop times are of type
timestamp with time zone
and the table is calledtimes
, you could use multirange magic and date arithmetic to find the answer:Use LAG() Over() analytic function to handle overlapings and calculate total difference in seconds (transform it later to hours,minutes,seconds if needed):
Using the instruction from https://dba.stackexchange.com/questions/270952/how-to-get-non-overlapping-distinct-intervals-from-a-postgresql-table
I applied your example (Exposing id, replacing f_time with StartTime, and replacing l_time with EndTime)
fiddle
Non-overlapping distinct intervals:
Total: