This is simple in theory, but difficult for me to figure out.
I have two SQL Server tables:
-
List of purchases with purchase date and total
select total, date from purchases -
list of miles traveled for a specific job and date of travel
select travelDate, miles from trips
EDIT: To keep the answer/discussion on my question, I am rephrasing the requirement.
I need to figure out the total miles driven between each purchase.
I want more accuracy than an overall average.
I can manually get this by summing all miles from trips in between each purchases date. Now, I just want to automate the process.
The grouping should be such that all trips dates greater than purchases date A and less than purchases date B are part of the purchases date A group.
Curing my denseness, I see that your request is quite reasonable by treating the problem as “replacement fuel cost”—thus using the fuel cost of the next fueling rather than the previous cost to buy the fuel actually used (which gets really complicated, really fast). Volume then doesn’t matter. Try this on for size.
Or here’s a version that thinks very differently about the problem but should give the same result. Let me know which one performs better, would ya? (
SET STATISTICS IO ON; SET STATISTICS TIME ON;)I apologize in advance for any typos or errors… I haven’t tested the code.
And just for laughs, here’s the first query transmogrified into a version that would work even on SQL Server 2000!
This actually exposes that I might not need to look up the previous purchase date in my first query, if I do it right… so here’s a final version:
Note: the order of the TripCost expression is important, because Miles and TotalMiles are integers. If you put P.Total last, you will get wrong answers because Miles / TotalMiles will be converted to an integer.