Reference Previous Row

Hi

I am attempting to reference the previous row in a non contiguous record set.

Recordset:

ID      Vehicle      Millage      
102      ABC123      10234
88      ABC123      99950
55      ABC123      99723

What I want to get from my query is:

ID      Vehicle      Millage       PMillage      
102      ABC123      10234             99950
88      ABC123      99950            99723
55      ABC123      99723            NULL

I have so far;

SELECT     c.ID, c.Volume, c.Vehicle, P.Millage AS PMillage, c.Millage
FROM         FuelOnly AS c LEFT OUTER JOIN
                      FuelOnly AS P ON c.Vehicle = P.Vehicle AND P.ID = c.ID - 1
WHERE     (c.Vehicle = N'C2 GBA')
ORDER BY c.ID DESC

This doe’s not work as the rows are non contiguous. How would I correct the query to return the required result I am using SQL 2008?




LVL 1
JoeBo747Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

deightonprogCommented:
how a bout a sub query to give the field, get the next highest id

SELECT     c.ID, c.Volume, c.Vehicle,
 (SELECT TOP 1 p.millage FROM FuelOnly P WHERE P.ID < C.ID AND P.Vehicle = C.Vehicle ORDER BY P.id DESC) AS PreviousMillage
 , c.Millage
FROM         FuelOnly AS c
WHERE     (c.Vehicle = N'C2 GBA')
ORDER BY c.ID DESC
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nitinsawhneyCommented:
Create a temp table with contiguous ids at the run time and then use that table for your query.

It should look like
temptable:
TID ID      Vehicle      Millage      
 3    102      ABC123      10234
 2    88      ABC123      99950
 1    55      ABC123      99723
0
JoeBo747Author Commented:
Hi Thanks for the example, I had looked at using cte but your method provides a much simpler solution. - thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.