Minimum with a correlated subquery mySql

bubi :

the Task is:Q: Show For each year, the month with the lowest temperature during the months with more than 150mm of rain.

I did this:

SELECT  year,month,tmin  
FROM table_name a
where rain>150 AND tmin= (SELECT MIN(tmin) FROM table_name b  WHERE b.tmin=a.tmin)

t.min is the minimum temperature in that month

When I run this, I get for each year the minimum temperature where the rain is >150mm

but there are rows like this:

year | month | tmin |
1866 | 1     | 3.8  |
1866 | 2     | 2.9  |
1866 | 11    | 11.1 |

and so on..

how do I get here the minimum of those 3 values, so that there is only one data from 1866 and not 3??

Did I do it wrong?

thanks

GMB :

It is a bit more complicated than you think. Not only your correlation clause needs to be fixed (it should match on years), but also you want the where condition in the subquery so you can filter on monthes that match the criteria on rain.

Overall, I think that it is easier to order by and limit in the subquery:

select year, month, tmin  
from table_name t
where month = (
    select t1.month
    from table_name t1
    where t1.year = t.year and t1.rain > 150
    order by t1.tmin, t1.month limit 1
) 

Note: the second ordering criteria is there to break the ties: in this case, the earlierst month of the year having the minimum temperature (and enough rain) is returned.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401725&siteId=1