SQL : Using GROUP BY and MAX on multiple columns

You can get the best attrib1 values, and then join in the attrib2 values and get the best of those for each attrib1 value:

select t2.catID, t2.attrib1, max(t2.attrib2)
from
(
  select catID, max(attrib1) as attrib1
  from test_table
  group by catID
) t1
inner join test_table t2 on t2.catID = t1.catID and t2.attrib1 = t1.attrib1
group by t2.catID, t2.attrib1

Use:

SELECT x.catid,
       x.max_attrib1 AS attrib1,
       (SELECT MAX(attrib2)
          FROM YOUR_TABLE y
         WHERE y.catid = x.catid
           AND y.attrib1 = x.max_attrib1) AS attrib2
  FROM (SELECT t.catid,
               MAX(t.attrib1) AS max_attrib1
          FROM YOUR_TABLE t
      GROUP BY t.catid) x

Tags:

Mysql

Sql