I have this query that calculates current gallons value from all fuel tanks in my database.
SELECT DISTINCT y.TankNumber as TankNumber
, y.Gallons as Gallons
, y.timeUpdated
, y.FuelType as FuelType
FROM (
SELECT TankNumber, max(timeUpdated) as maxdate
FROM someTable
GROUP BY TankNumber) as x
JOIN someTable y
ON x.TankNumber = y.TankNumber
AND x.maxdate = y.timeUpdated
ORDER BY y.TankNumber
Based on the fuel usage, data gets dumped in to my database automatically at any time. And query above will give me only the current gallons value in each fueltank:
TankNumber | Gallons | timeUpdated | FuelType
1 | 14 | 2012-10-22 04:16 | 89
2 | 8 | 2012-10-22 04:14 | 93
and etc..
My problem is, that I am trying to add another output value to my page, that will give me a difference how much fuel was used since last update. So it will look something like this:
TankNumber | Gallons | timeUpdated | FuelType | GallonsUsed
1 | 14 | 2012-10-22 04:16 | 89 | 5
2 | 8 | 2012-10-22 04:14 | 93 | -11
Unfortunately my SQL experience is not as solid for this type of problem and I have spent about two days trying to figure out or google something close. So, any help will be greatly appreciated.
Assuming you’re using MS SQL 2005 or later, you can use the ROW_NUMBER function: