I have a table that contains call detailed records with the following structure (simplified):
CREATE TABLE public.cdr (
call_id int8,
start_date timestamp,
duration_ms int4
)
I need to calculate average call duration per time range:
So the result table look something like this.
range_start |avg_duration_ms | number_of_calls_in_range
-----------------------+----------------+-------------------------
2023-05-15 15:00:00.000| 65230 | 12
2023-05-15 15:05:00.000| 3450 | 67
2023-05-15 15:10:00.000| 28329 | 25
I can't comprehend how to get an average over the part of the call that falls within a certain range, rather than the total call duration.

This is much easier to do when using range data types, like tsrange. You need a start- and enddate for the call and then you can calculate the time spent in each frame.
Something like this:
You can change the interval result into seconds or milliseconds, whatever fits best.
Result: