Anders Anders - 3 months ago 6
MySQL Question

SQL retrieving highest number from each group

I have a MySQL-table, containing these data:

idPK groupIDFK
1 1
2 1
3 2
4 2
5 1


I'm looking for a way to group the 2nd column values and display the highest value from the first column in that group. In this case, it should return these entries:

idPK groupIDFK
5 1
4 2


Does my description make sense? And if so, can someone please help me out?

Answer

This is your query where rows are sorted by groupIDFK:

select max(idPK) as idPK, groupIDFK from table group by groupIDFK;

If you need to order by idPK below is another version:

 select max(idPK) as idPK, groupIDFK from table group by groupIDFK order by idPK desc;
Comments