Bring certain field, by MAX(ID)

Asked

Viewed 2,142 times

0

How do I bring in any field, by the largest table ID. I did a MAX(Campo1), Campo2 and had to make a grouping by Campo2 and the result he brought me several Campo2 and not only one, which has the highest ID.

Select MAX(ID), campo2 from tabela where campo3 = valor group by campo2

This did not work, brought me several field2

  • You want to get a certain record field with the highest ID?

2 answers

2

If you simply want to bring the largest table id, only this solves:

Select MAX(ID) from tabela;

After all, Id is unique and does not need to group values.

If you need to bring another field based on MAX(ID), the correct is:

select campo2
from tabela
where ID = (select MAX(ID) from tabela);
  • Yes, but I need to bring the other field by this max id. I need the field2 in reality, based on this MAX(ID), as I do this?

  • @pnet I updated the response.

0

So you did, but I had to put a subquery in the play

select campo2 from tabela where campo3= 49 and campo1  in (select max(campo1) from tabela where campo3 = 49)

So you decided.

Browser other questions tagged

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