Skip to content
Advertisement

Calculate differing accumulated storage charges over time?

I am working on a project for a wine importer, in which need to calculate the accumulated storage charges per SKU up to the delivery date.

I have data from the warehouse recording the Date_In and Date_Out so calculating DATEDIFF('day', Date_In, Date_Out) is fairly trivial. However every year the warehouse changes its prices, so when calculating the storage charges I need to split my Days_in_Stock across differing rates.

Input data with stock movement dates:

Storage rates:

My desired output is as follows:

DAYS_IN_STOCK is calculated with DATEDIFF('day', Date_In, Date_Out)

STORAGE_COST is COST_PER_WK * DAYS_IN_STOCK / 7

The issue I have is where as with Invoice 1002 the DAYS_IN_STOCK spans more than one charge rate. In which case the calculation needs to be something like:

Ideally the final query would be able to handle cases where the item has been in stock for more than 2 charge rate periods too.

Approaches attempted so far:

  • Hard coding the query to find number of days before and after the rate change, but I will eventually need to use data going back 5 years and implement the same thing for a much more complicated delivery rate table.
  • Trying to JOIN Date_In to Date_Effective, but I couldn’t get it to work, and have no idea how I would extend to 3 price rates.

I’m fairly stumped as to how to tackle this so any ideas would be very welcome. Currently using SQL Server 2017

Advertisement

Answer

This should give you an idea on how to solve this. I don’t want to deal with weeks, so I’ll phrase this answer in terms of days.

The basic idea is to add an end date to the rates table, then use join and aggregation:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement