3

I have a table where I store invoices of spent fuel and the km's where the car was refueled, with the following structure:

enter image description here

My goal is to obtain a result like the following, so I can calculate the spent km's beetween invoices.

enter image description here

Any advice regarding how I can structure the query to get the desired result?

6
  • Are these all records about a single car? Commented Mar 15, 2013 at 11:21
  • Which RDBMS are you use? Commented Mar 15, 2013 at 11:21
  • yes @Kaf, only related to a single car. Commented Mar 15, 2013 at 11:25
  • @KevinBrydon, Really? Commented Mar 15, 2013 at 11:30
  • @KevinBrydon Do you see that OP is edited and can you compare the times? Commented Mar 15, 2013 at 11:39

3 Answers 3

2
SELECT Date,
       (SELECT MAX(Kms) FROM invoices i2 WHERE i2.Kms < i1.Kms) AS StartKm,
        Kms AS FinishKm
FROM invoices i1
ORDER BY Kms

See: SQL Fiddle Demo.

Sign up to request clarification or add additional context in comments.

Comments

2
;WITH Invoices AS 
(
    SELECT 456 AS Invoice, '2013-03-01' AS [Date], 145000 AS Kms
    UNION ALL
    SELECT 658 AS Invoice, '2013-03-04' AS [Date], 145618 AS Kms
    UNION ALL
    SELECT 756 AS Invoice, '2013-03-06' AS [Date], 146234 AS Kms
), OrderedInvoices AS
(
    SELECT Invoice, [Date], Kms, ROW_NUMBER() OVER(ORDER BY [Date]) AS RowNum
    FROM Invoices
)

SELECT i1.[Date], i2.Kms AS StartKms, i1.Kms AS FinishKms
FROM OrderedInvoices AS i1
LEFT JOIN OrderedInvoices AS i2
    ON i1.RowNum = i2.RowNum + 1

Comments

1

Using CTE and Row_number():

;with cte as (
   select Invoice, [Date], kms, row_number() over(order by [date]) rn
   from yourTable
)

select c1.[Date], c2.kms StartKms, c1.kms EndKms
from cte c1 left join cte c2 on c1.rn  = c2.rn +1
order by c1.[Date] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.