Pull the last information from a table

Asked

Viewed 106 times

0

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

in my Route table have the columns Id(PK), Date, Current Km_and Nveiculoid(CK).

In this table I need to take the last Km_current typed and compare with what was already registered in that vehicle that would be the Nveiculoid.

Use an SQL SERVER.

1 answer

0


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

With subselect the previous Km_column is generated, you can use it as you like.

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
  • Then I won’t need to create Km_previous? and instead of Data it wouldn’t be Km_current?

  • can be, remembering that in both cases, you have to have some validation of this so that the user does not report a km smaller than the previous one, or a retroactive date with a km greater than the current one.

  • I understand, I need to put this comparison on a site I’m creating, is in Asp.net with Brazilian, before they add it will take these values and compare, however it is a table of route so a car, bike or vehicle can walk several times in the same day

  • I see no problem if the date field is like Datetime, which will also consider the time. But if the ID is sequential and can not be updated in the table, would for it

  • I’d do it by the date, I get it, try to apply it to the code and I really appreciate the help

  • for nothing, don’t forget to mark as a response if it helped you. =]

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.