Skip to content
Advertisement

How do I join two tables based on a minimum value in the first table?

I have two tables: one has a list of weather stations near major cities and the distance to the city, and the other has weather averages for each weather station. I want to do a join such as showing weather data from the station closest to San Francisco.

Example table distances:

Example table weatherdata

I’d like to be able to do an SQL select based on the city name.

Advertisement

Answer

For one city, I would suggest:

For all or multiple cities, I would just tweak this using distinct on:

Both of these version can use an index on distances(city, distance).

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