SQL to group records

Asked

Viewed 20 times

0

I made the query below to load the records with the highest date of exit (a same record may have several dates):

SELECT   RA, MAX(Data_Out) AS Data_Saida, Placa
FROM     dbo.RA_Vehicles
GROUP BY RA, Placa
ORDER BY RA

I’m having difficulties when I include the column placa (carries all records). In short, I need a query that loads the contracts and their plates with the longest date of exit (the 30 contract for example, can have two records, one with the A and X data plates and the other with the B with Y date plates. I need to load only the record with the longest date).

It would have to use an under-consumption?

  • is using sql server? mysql?

  • I am using SQL server

  • I think the best thing is to do with subconsulta msm.. like this https://stackoverflow.com/a/44064826/4551469

1 answer

1


As commented, I believe that the ideal in the solution is even with subconsulta, similar to this other answer of ONLY.

//inner join
SELECT v1.RA, v1.Placa, v1.Data_Out AS Data_Saida
FROM dbo.RA_Vehicles v1
INNER JOIN (
    SELECT RA, MAX(Data_Out) Data_Out AS Data_Saida
    FROM dbo.RA_Vehicles
    GROUP BY RA
) v2
ON v1.RA = v2.RA AND v1.Data_Out = v2.Data_Out

There are other ways to make the comparison, and if there is concern with performance you can analyze possible solutions, as suggested at that link.

  • 1

    Gave right friend... Thank you very much... Helped me a lot!!!

  • pasta, @Saul!! = ) remember to mark the answer as ;) and qq thing, send more question up..

  • 1

    can you leave... Thanks

Browser other questions tagged

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