I have a database table that contains collection data for product collected from a supplier and I need to produce an estimate of month-to-date production figures for that supplier using an Oracle SQL query. Each day can have multiple collections, and each collection can contain product produced across multiple days.
Here’s an example of the raw collection data:
Date Volume ColectionNumber ProductionDays 2011-08-22 500 1 2 2011-08-22 200 2 2 2011-08-20 600 1 2
Creating a month-to-date estimate is tricky because the first day of the month may have a collection for two days worth of production. Only a portion of that collected volume is actually attributable to the current month.
How can I write a query to produce this estimate?
My gut feeling is that I should be able to create a database view that transforms the raw data into estimated daily production figures by summing collections on the same day and distributing collection volumes across the number of days they were produced on. This would allow me to write a simple query to find the month-to-date production figure.
Here’s what the above collection data would look like after being transformed into estimated daily production figures:
Date VolumeEstimate 2011-08-22 350 2011-08-21 350 2011-08-20 300 2011-08-19 300
Am I on the right track? If so, how can this be implemented? I have absolutely no idea how to do this type of transformation in SQL. If not, what is a better approach?
Note: I cannot do this calculation in application code since that would require a significant code change which we can’t afford.
try
The view
DailyProdVolEstgives you dynamically the result you described… though some “constraints” apply:ProdDateandCollectionNumbershould be unique.ProductionDaysneed to be > 0 for all rowsEDIT – as per comment requested:
How this query works:
It finds out what the smallest + biggest date in the table are, then builds rows with each row being a date in that range (
DateList)… this is matched up against a list of rows containing the daily sum for unique combinations of ProdDate Start/End (DateRangeSums) and sums it up on the date level.What do
SUM (DateRangeSums.DailySum)andSUM (DailyProduction)do ?Both sum things up – the
SUM (DateRangeSums.DailySum)sums up in cases of partialy overlapping date ranges, and theSUM (DailyProduction)sums up within one date range if there are more than oneCollectionNumber. WithoutSUMtheGROUP BYwouldn’t be needed.