mysql - SQL Select only rows with Max Value on a Column revisited -


same old question:

i have table. want rows max value field, grouped set of fields. not need max value , group fields, need full row (all other fields, can't do:

select max(field1),  field2 table group field2;  

as said, need field3, field4, ... , fieldn.

this has been treated before, , found excelent answer here:

sql select rows max value on column

basically, says should join between original table, getting fields there, , subquery gets me max , group fields. , cases, works.

my issue

for particular case not sure approach works, because of data types involved. let me give example.

consider gives me max values want, grouped field want:

select max(field1) maxf1, field2 f2 mytable group f2 

the above link suggest trying like:

select mt.field1, mt.field2, mt.field3, ... , mt.fieldn mytable mt inner join (     select max(field1) maxf1, field2 f2 mytable group f2 ) sq on sq.maxf1 = mt.field1 , sq.f2 = mt.field2 

for particular case, field1 , field2 may of type float , timestamp. therefore, join comparisons sq.maxf1 = mt.field1 , sq.f2 = mt.field2 might not way go (see what effective way float , double comparison?). so, hints me on one?

your query fine:

select mt.field1, mt.field2, mt.field3, ... , mt.fieldn mytable mt inner join ( select max(field1) maxf1, field2 f2               mytable group f2            ) sq    on sq.maxf1 = mt.field1       , sq.f2 = mt.field2 

max() or min() not result in float rounding issues, if aggregating or performing other calculations concern, wouldn't using field join anyway.

fyi: if doing other conversion or trying join using float on 1 side , decimal on other common method choosing acceptable margin of error , using absolute value , subtraction:

select mt.field1, mt.field2, mt.field3, ... , mt.fieldn mytable mt inner join ( select max(field1) maxf1, field2 f2               mytable group f2            ) sq    on abs(sq.maxf1 - mt.field1) < .0001      , sq.f2 = mt.field2 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -