SQL : Using GROUP BY and MAX on multiple columns SQL : Using GROUP BY and MAX on multiple columns sql sql

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) t1inner join test_table t2 on t2.catID = t1.catID and t2.attrib1 = t1.attrib1group 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


SELECT tt.catId, tt.attrib1, MAX(tt.attrib2)FROM   test_table ttGROUP BY tt.catID, tt.attrib1WHERE  tt.attrib1 = (SELECT MAX(t2.attrib1) FROM test_table t2 WHERE t2.catID = tt.catID)