Average days in transition status till the end of period

Hi!
I need to build statistics to calculate the average time spent by a task in status, quarterly at the end of each period, taking into account all tasks. I plan to do it like this:

  1. Get all tasks created for the entire time until the end of the period (both open and closed tasks must be taken into account)
  2. Calculate the average time in status (if the task is still in status, then it is necessary to take into account the number of days spent in status until the end of the period)
  3. Build quarterly statistics that will show how many working days on average all tasks were in status (for example, in progress) as of the end of each period.

To solve this problem, I planned to use the filter “Days in transition status till now”, but it counts the time in status until the current moment, and not until the end of the period, which prevents me from building quarterly statistics. It is also necessary to take into account closed comments.