I have a table used to enter weekly Hobbs hour meter readings for vehicles. I need to be able to add up the total hours used for each vehicle over a period of time. The problem I am having is that sometimes the meters get swapped out once they fail and are replaced with new meters the are not programmable and I have to start at zero hours so I will need to loop through each meter reading and determine if a meter had been swapped and account for it in my code. I’m not big on cursors but may have to use one to create a stored procedure that will work unless someone has a better solution I should try. I’m trying to think of a way a CTE might help but nothing yet.
The table structure is:
ReadingDate Datetime
EquipmentId Int
MeterReading decimal(18,2)
I.m planning on Creating a accumulation variable, loop through the rows in a cursor and add the reading difference into the variable.
So as I loop through and see a meter reading is less than the previous reading, I must have a meter swap out and will have to account for it. I’m thinking that if I was to look ahead at the next reading and it is lower than the current, I would just skip the summing action one time and then start adding the difference to the accumulation variable. Any better way to do this? Thanks.
This will work in SqlServer:
SQL Fiddle I was playing with