I have a large number of date ranges as below, example below. I need to calculate how many months are in each actual calendar year. So this would break down as:
Contract: 123
Start date: 01/11/2016
End date: 01/06/2018
- 01/11/2016 > 31/12/2016 - 2 months in year 2016
- 01/01/2017 > 31/12/2017 - 12 months in year 2017
- 01/01/2018 > 01/06/2018 - 6 months in year 2018
Contract: 456
Start date: 31/05/2017
End date: 01/06/2019
- 31/05/2017 > 31/12/2017 - 6 months in year 2017
- 01/01/2018 > 31/12/2018 - 12 months in year 2018
- 01/01/2019 > 01/06/2019 - 6 months in year 2019
Does anyone know of a solution to handle this? Each contract has a row, all in the same table and the start and end date listed in the same row.
I was originally going down the CTE route but this blew my mind.
Expected outcome:
contract_id year number of months
123 2016 2
123 2017 12
123 2018 6
456 2017 6
456 2018 12
456 2019 6
Or similar, I am more than happy to amend my original query to incorporate what the best outcome/method to achieve this is.
Table definition:
- contract_id: int
- start_date: datetime
end_date: datetime
contract_id start_date end_date 123 2016-01-11 00:00:00.000 2018-06-01 00:00:00.000 456 2017-05-31 00:00:00.000 2019-06-01 00:00:00.000