CodeGuy
CodeGuy

Reputation: 28905

Selecting the row with the max in a column - MySQL

I have the following table called MyTable

    First     Second     Third    Fourth
    1         Ab         Cd       2.3
    1         Cq         Fe       3.4
    2         Dr         Dh       1.2
    3         Bb         Qd       9.8
   ..........ETC.....................

How can I select the rows grouped by First that have a maximum Fourth column value. So it would be a query that results in

    First     Second     Third    Fourth
    1         Cq         Fe       3.4
    2         Dr         Dh       1.2
    3         Bb         Qd       9.8

Upvotes: 2

Views: 139

Answers (3)

roman
roman

Reputation: 117540

select
    B.*
from (select T.First, max(T.Fourth) as Fourth from Table as T) as A
    inner join Table as B on B.First = B.First and B.Fourth = A.Fourth

Upvotes: 0

Robert
Robert

Reputation: 25763

Try this solution:

select MT.First, MT.Second, MT.Third, MT.Fourth 
from MyTable MT
join ( select first, max(Fourth) as Fourth
       from MyTable
       group by first
     ) T on T.first = MT.First
         and T.Fourth = MT.Fourth

SQL Fiddle Demo

Upvotes: 2

Joe G Joseph
Joe G Joseph

Reputation: 24096

try this:

select * 
from   MyTable T
join      (Select First,max(Fourth) as Fourth
          from MyTable
          group by First)a
on    T.First=a.First
and   T.Fourth=a.Fourth


SQL Fiddle Demo

Upvotes: 5

Related Questions