The context of this problem is a billing system for a warehouse that stores widgets. The storage fee is based on the size of the widget (e.g $x * height * length * width). This part is easy. I use the following SQL to calculate Amount Due and aggregate by user id.
Select UserID, Sum((Height * Length * Width * 5) as AmtDue From Widget
Where StatusID=2
Group By UserID
5 is an arbitrary value for the moment. Eventually I’ll pass it as a parameter or get it from a table in the database. Assume it’s always 5 for the moment.
Here’s the part I’m struggling with. Fees are calculated at the end of the month and are prorated according to the number of days in that month the widget was stored in the warehouse (e.g. if the widget sits in the warehouse for 15 days out of a 30 day month the fee due is 50% of the amount). In my Widget table I have a column for DateReceived and DateShipped. DateReceived always has a datetime value. DateShipped is sometimes null (e.g. if the widget is still in storage). I have parameters available for CycleStart and CycleEnd which represent the start and end of the relevant billing month. I’m trying to modify my SQL query to include in the select expression a prorate factor that is equal to (# of days in storage / # of days in month). In other words AmtDue becomes (height * length * width * 5 * prorate factor) How do I do this?
Here’s an example to help illustrate how the prorate factor is calculated.
If @CycleStart = 7/1/11 and @CycleEnd = 7/31/11 mm/dd/yy
DateReceived | DateShipped | Prorate Factor
6/5/11 Null 100%
6/5/11 7/15/11 48.38%
7/30/11 8/5/11 6.45%
7/15/11 7/25/11 35.48%
I’m really struggling with the conditional nature of this and the fact that we’re dealing with datetime values.
Here you go. This
Yields the following