Same old question:
I have a table. I want the rows with max value for a field, grouped by a set of fields. BUT I do not need JUST the max value and group by fields, I need the full row (all other fields, so I can't just do:
select max(field1), field2 from table group by field2;
As I said, I need field3, field4, ... , fieldn.
This has been treated before, and I found an excelent answer here:
SQL Select only rows with Max Value on a Column
Basically, it says I should do a join between the original table, getting all fields from there, and a subquery that gets me the max and group by fields. And for most cases, that probably works.
My issue
For my particular case I am not so sure that approach works, because of the data types involved. Let me give an example.
Consider this gives me the max values I want, grouped by the field I want:
select max(field1) maxf1, field2 f2 from mytable group by f2
The above link would suggest trying something like:
SELECT mt.field1, mt.field2, mt.field3, ... , mt.fieldn
FROM mytable mt
INNER JOIN (
SELECT max(field1) maxf1, field2 f2 FROM mytable GROUP BY f2
) sq
ON sq.maxf1 = mt.field1 AND sq.f2 = mt.field2
For my particular case, field1 and field2 may be of type FLOAT and TIMESTAMP. Therefore, the join comparisons sq.maxf1 = mt.field1
and sq.f2 = mt.field2
might not be the way to go (see What is the most effective way for float and double comparison?). So, any hints for me on this one?