Skip to content
Advertisement

Query that returns maximum and corresponding FK(ID) group by year which comes from another select that has averages group by FK(ID) and year

I have a raw table which contains the id (pk AI), farm_fk (or HERD), birthdate, nm (some indicator).

I want to get the maximum of nm averages for each existing year and corresponding farm_fk.

What is DID?

1st from table I got the averages of nm for each farm_fk group by year which returns some thing like this I added the inner select query (here I added order by also to ease of reading)

Output:

Secondly, I tried to extract the max of (avg(nm)) for each year and corresponding herd and I tried this

Which does not work properly since I think according to what I need its wrong to group by HERD and also there are many HERD in previous select for each year. without HERD column in above query I get this which is correct but without corresponding herd id

Advertisement

Answer

I think you just want to use ROW_NUMBER():

Note that in the event of ties, this returns just one of the ties. If you want all of them, use RANK() instead of ROW_NUMBER().

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement