Pulling the last information from a table [closed]

0

I wanted to know how to pull the last information that was registered in the bank, but I can not use the ID.

In my Route table you have the columns Id (PK), Date, Current_Malue, Combustivel and NVeiculoId (CK).

In this table I need to get the last Km_Atual typed and compare with what was already registered in that vehicle that would be the NVeiculoId.

I use a SQL SERVER.

    
asked by anonymous 03.07.2017 / 21:31

1 answer

0

Some order is necessary to follow, in this code I used the date, and if they are the same it follows the ID.

With the subselect is generated the column Km_Previous, done that you can use it as you want.

SELECT
ID,
Data,
Km_Atual, 
Combustivel,
NVeiculoID,
    (SELECT TOP 1
         x.Km_Atual 
     FROM rota x 
     WHERE x.NVeiculoID  = r.NVeiculoID
     AND x.ID != r.ID
     AND x.Data < r.Data
     Order By x.Data desc, x.ID desc) as Km_anterior
FROM rota r
    
03.07.2017 / 21:45