Get last record of each id in sql query on condition

Asked

Viewed 2,579 times

1

I’m having trouble getting the last record of each id in an SQL Server table.

select c.Serial,v.Descricao,v.Placa,v.Cor,v.AnoFabricacao,v.Chassi
c.DataHora,c.Endereco from [CheckPoint] c inner join Equipamento e on e.Serial= c.Serial
inner join Veiculo v on v.Codigo=e.CodigoVeiculo 
where v.Codigo in(44,45)
group by v.codigo,c.Serial,v.Descricao,v.Placa,v.Cor,v.AnoFabricacao,v.Chassi
,c.DataHora,c.Endereco
order by 
c.DataHora desc

This query this returning me the following data in that order, I would like you to show me the most current record of each code.

inserir a descrição da imagem aqui

  • You can set an example, or indicate which output you want to get?

  • I need to Get the most current record of each ID ! that is, the query has to return 2 lines!

  • You can check below, my reply, to see if it returns the expected result?

2 answers

3


I understand that when you say the last record you want the one with the most current date.

select c.Serial,
       v.Descricao,
       v.Placa,
       v.Cor,
       v.AnoFabricacao,
       v.Chassi,
       max(c.DataHora) as DataHora,
       c.Endereco 
from [CheckPoint] c 
inner join Equipamento e 
   on e.Serial= c.Serial
inner join Veiculo v 
   on v.Codigo=e.CodigoVeiculo 
where v.Codigo in(44,45)
group by v.codigo, c.Serial, v.Descricao, v.Placa, v.Cor, v.AnoFabricacao, v.Chassi, c.Endereco
order by c.DataHora desc

or

select Serial,
       Descricao,
       Placa,
       Cor,
       AnoFabricacao,
       Chassi
       DataHora as DataHora,
       Endereco
from
(
    select c.Serial,
           v.Descricao,
           v.Placa,
           v.Cor,
           v.AnoFabricacao,
           v.Chassi
           c.DataHora as DataHora,
           c.Endereco,
           row_number() over (partition by v.Codigo order by c.DataHora desc) rn
    from [CheckPoint] c 
    inner join Equipamento e 
       on e.Serial= c.Serial
    inner join Veiculo v 
       on v.Codigo=e.CodigoVeiculo 
    where v.Codigo in(44,45)
    group by v.codigo, c.Serial, v.Descricao, v.Placa, v.Cor, v.AnoFabricacao, v.Chassi, c.DataHora, c.Endereco
    ) Resultados
    where rn = 1
    order by DataHora desc
  • This example the query is not correct ah some errors

  • In the first example a comma was missing. I corrected both.

  • Thank you very much!

0

  • this my condition Where v.Code in(44,45) // field Code ids are variables or I will query with other ids

  • have tried with RETURNING? or WHERE v.Codigo = @id_1 OR v.Codigo = @id_2

  • You can show me an ex

Browser other questions tagged

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