tags:

views:

87

answers:

3

SELECT MAX(some_field) FROM table_A GROUP BY another_field.

this only get the max value of the 'some_field', I wanna get the whole record which contains the MAX(some_field).

thanks.

+5  A: 
select a.*
from table_A a
inner join (
    SELECT another_field, MAX(some_field) as MaxSomeField
    FROM table_A 
    GROUP BY another_field
) am on a.another_field = am.another_field and a.some_field = am.MaxSomeField
RedFilter
Beat me to it. ;) +1
Tomalak
+4  A: 
SELECT
  *
FROM
  table_A
  INNER JOIN (
      SELECT MAX(some_field) AS some_field, another_field
        FROM table_A
    GROUP BY another_field
  ) AS max ON table_A.some_field    = max.some_field
          AND table_A.another_field = max.another_field

Note that you will get multiple rows of another_field if MAX(some_field) is not a unique value in that group. You'd have to group the above again to get rid of those "duplicates".

Tomalak
+1  A: 
Select * From table_A withMax Where Not Exists
    (Select * From table_A Where some_field > withMax.some_field)

Usually, you'll be doing that with some other criteria, and you'll want to check for duplicates, so a realistic example is more like this:

Select * From table_A withMax Where account_id = 1234 Not Exists
    (
    Select * 
    From table_A 
    Where account_id = withMax.account_id And 
        (
        some_field > withMax.some_field
        Or (some_field = withMax.some_field And id > withMax.id)
        )
    )
PstScrpt
thanks, you give me a new way to solve this question.
lovespring
compare to 'inner join', which is faster?
lovespring
It tends to be different in every database and version; it could go either way. I like this style for readability and ease of adding more conditions.I did just notice you had this tagged as MySQL, and I don't know how well it's supported there. I've used it in Oracle and SQL Server.
PstScrpt