This is SQL Server 2000 so I don’t have any windowing functions (row_number).
I have a table emp_data :
emp_id datime miles gallons
23148 2011-08-21 02:00 32 3
23148 2011-08-21 09:00 38 4
23148 2011-08-21 11:00 40 5
42938 2011-08-20 03:00 23 1
42938 2011-08-22 08:00 53 13
- Each row is cumulative (running?) from the previous one.
I need to get the number of miles driven by the employee, which I do by subtracting the miles for the earliest date minus the miles for the latest date. (40-32 = 8 miles driven for empid=23148). I need to do this for gallons too.
I need to calculate miles per gallon for each driver.
The end result should be this:
emp_id miles gallons
23148 8 2
42938 30 12
Doing it for multiple drivers is where I’m stuck. In SQL Server 2005, I could probably do row_number partition_by, but don’t know what to do in SQL Server 2000. I’ve done something like this for one driver. Won’t work partitioned by drivers. Had to use identity() in place of row_number.
SELECT IDENTITY(int) as id, emp_id, datime, miles, gallons
into #t1
FROM emp_data
where
emp_id='18018'
and datime >= '20110820 02:00'
and datime <= '20110827 02:00'
ORDER BY datime
select foo1.emp_id,foo2.miles - foo1.miles as miles_driven,
foo2.gallons - foo2.gallons as gallons_used
from (
SELECT *
FROM #t1
where id = 1) foo1
CROSS JOIN (
SELECT *
from #t1
where id = (select max(id) from #t1 t)
) foo2
I do have a linked server to the SQL Server 2000 db from SQL Server 2008 so I’m thinking of getting the data and then processing there, but there’s about 1 million records for just one week. I might need to do this for YTD.
Let me know if something is unclear. Sorry I don’t have any sample data.
I think this is what you’re looking for (no need for temp tables) but only use if you have additional data constraints that we’re not seeing. Otherwise go with smdrager answer