Skip to content
Advertisement

Cumulative elapsed minutes on hourly basis in PostgreSQL

I have a datetime column. I need to derive a column of total minutes elapsed from the first to the last value of every hour grouped by hour, but, in cases of overlapping event, the time should be distributed between two hours. There is also a condition where if the elapsed time exceeds 30 minutes in between two consecutive records, then it has to be ignored.

Below, I’ve explained in three phases, Original, Intermediate (calculating the running total) and Final.

enter image description here

And, I’m planning to take hourly incremental data on the same, so, how can we properly merge it with the old data is another question.

Sample data:

Intermediate layer:

Final Output:

Advertisement

Answer

This is a gaps-and-islands problem with some twists. First, I would summarize by the “islands” defined by the gaps of 30 minutes:

Then you can use this with generate_series() to expand the data and calculate the overlaps with each hour:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement