0

I have the following table called my_values in a MySQL 5.7 database:

value1 value2 value3
foo 7 something4
foo 5 something1
foo 12 anything5
bar 3 something7
bar 18 anything5
bar 0 anything8
baz 99 anything9
baz 100 something0

As you see, there are duplicates in value1. I want to SELECT each unique value1 only once, but that row with the highest value in value2.

I'm using this query for that:

SELECT v.* FROM my_values v WHERE v.value2 = (SELECT MAX(v2.value2) FROM my_values v2 WHERE v2.value1 = v.value1);

The result is:

value1 value2 value3
foo 12 anything5
bar 18 anything5
baz 100 something0

Here's a fiddle of that.

From this result I want to SELECT each unique value3 only once, but that row with the highest value in value2 (no matter what value1 is).

So expected result would be:

value1 value2 value3
bar 18 anything5
baz 100 something0

How can I do that?

David
  • 2,898
  • 3
  • 21
  • 57

2 Answers2

1

here is how you can do it :

select t1.*
from my_values t1
natural join (select value1, MAX(value2) value2
               from my_values 
               group by value1 ) t2
natural join (select value3, MAX(value2) value2
               from my_values 
               group by value3) t3

fiddle

eshirvana
  • 23,227
  • 3
  • 22
  • 38
0

You can use tuples for the comparison:

select t.*
from my_values t
where (t.value2, t.value3) = (select t2.value2, t2.value3
                              from my_values t2
                              where t2.value1 = t.value1
                              order by t2.value2 desc, t2.value3 desc
                              limit 1
                             );
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786