Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query - Filtered value from specific rows into result

Tags:

sql

sql-server

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?

like image 973
Filipe Costa Avatar asked Aug 10 '26 10:08

Filipe Costa


2 Answers

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.

like image 108
Steve Chambers Avatar answered Aug 11 '26 22:08

Steve Chambers


;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
like image 21
Dis Shishkov Avatar answered Aug 11 '26 22:08

Dis Shishkov