I’ve got two tables called hotels and hotel locations. In the hotels table I have HotelId, hotelName. In the hotelLocations table I have HotelId, HotelNorthing, HotelEasting. HotelId is a foreign key that references HotelId in the hotels table, HotelNorthing and HotelEasting are UTM co-ordinates that hold the northing and easting values for the hotels.
I would like to find, using this data the 2 hotels that are closest to each other and display with a query the hotel name and id from the hotels table and the distance from the calculation. I previously tried all sorts of cross joins but came up short. I used the Pythagoras theorem to calculate the distance between the hotels but the structure of an appropriate query has eluded me.
Assuming MS SQL 2008 or later I’d use the built in geography type:
This will give you the distance from Hotel1 to all the other hotel’s, then it’s just a matter of sorting the list and taking the top 2.
EDIT: To calculate from every hotel to every other hotel:
EDIT 2:
Split Hotel Names out into seperate table: