Suppose I have the data set below:
contract line item effectiveDate termDate rate
1234 1 ITEM1 10/12/2005 4/4/2016 $100.00
1234 1 ITEM1 5/1/2015 4/4/2016 $125.00
1234 1 ITEM2 10/12/2005 4/4/2016 $200.00
1234 1 ITEM2 5/1/2015 4/4/2016 $225.00
1234 2 ITEM3 10/12/2005 4/4/2016 $300.00
1234 2 ITEM3 5/1/2015 4/4/2016 $325.00
1234 3 ITEM4 10/12/2005 4/4/2016 $400.00
1234 3 ITEM4 5/1/2015 4/4/2016 $425.00
Given the start date of 1/1/2015 and the end date of 12/31/2015, I need to get a count of how many days each rate was active during the period. For example:
ITEM1, Line 1: $100 was effective 10/12/2005 through 4/30/2015. Since we're only interested in 1/1/2015-12/31/2015, this is actually only active 1/1/2015-4/30/2015.
$125 was the effective rate beginning 5/1 through 4/40216. Since we're only interested in 1/1/2015-12/31/2015, this is actually only active 5/1/2015-12/31/2015.
This item was active at $100 for 120 days and at $125 for 245 during the period being examined. I would like these values added as a column for each row.
How can I calculate this as part of a TSQL statement? I've built a separate application that handles this outside of the database layer, but there is a new requirement that a legacy reporting tool needs to consume this directly from SQL, so I need to find a way for SQL to prepare this data.
Any thoughts would be appreciated.