'Return Monthly Revenue based on a start and end dates

I am looking to create a query that would return the individual monthly revenue for the next 12 months. The revenue amounts are currently stored by projectid and an associated start and end date. I would need to spread that revenue across the date ranges and then find the sum for each month.

|projectid |startdate | enddate | revenue |------------|----------|--------------|---------
| 1461 |2022-09-13| 2022-09-22| 300000 | 1586 |2023-04-01| 2023-04-03| 66000 | 17955 |2023-01-30| 2023-02-14| 14240 | 24450 |2023-02-20| 2023-03-06| 360450 | 27598 |2023-11-27| 2023-12-21| 120000 | 28133 |2023-08-17| 2023-08-23| 280000 | 29593 |2022-12-19| 2022-12-22| 26400 | 29768 |2023-12-13| 2023-12-25| 551254 | 32664 |2022-06-26| 2022-07-17| 98247.42 | 2012 |2022-10-19| 2022-10-25| 19500 | 18539 |2022-10-28| 2022-11-04| 200000 | 32957 |2023-07-21| 2023-07-28| 18000 | 13553 |2024-02-20| 2024-02-26| 650000 | 17680 |2022-05-29| 2022-06-06| 80000 | 18201 |2024-01-10| 2024-01-24| 45000 | 21435 |2024-03-23| 2024-03-27| 30000 | 23695 |2023-02-21| 2023-03-03| 213400 | 25517 |2023-01-15| 2023-01-24| 180000 Essentially what I would like to do is:

  1. determine the daily revenue for each project so something like
revenue/(DATEDIFF(DAY,startdate,enddate) + 1)
  1. determine how many days in each month the project spans which should be 4 different cases,
  • Case 1: the projects start and end date is within the selected month,
  • Case 2: the projects start before the month start and ends within the selected month,
  • Case 3: the projects start in the selected month and ends after the month-end,
  • Case 4: the project starts before the selected month and ends after the selected month.

This is where I'm struggling to create those cases and get the number of days each project has within the selected month.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source