I’ve got a really complicated query that I need do but I just can’t seem to get my head around how to accomplish it so I’m hoping someone can help me.
I have two queries which I need to make into one query.
My first query is this:
select * from table1 t1
join table2 t2 on t2.outcode = t1.post_code
This produces results which include LAT and LONG of the postcode like so:
Name Postcode Lat Long
Taylor CB8 53.829517 -1.780320
These are just dummy values for test purposes.
My next query is this
SELECT * FROM (
SELECT t3.location_name,
calc_distance(t3.lat, t3.lng, t2.lat,t2.lng) as distance
FROM table3 t3, table2 t2
where t2.outcode = :postcode
order by distance) i
where rownum = 1
calc_distance is a function that calculates the distance based on LAT & LONG of a point
If I substitute :postcode with CB8 it produces these results
Location_name Distance
NR Location 56.6
What I somehow need to do is produce the following output from a single query.
Name Postcode Lat Long Nearest_Loc Distance
Taylor CB8 53.829517 -1.780320 NR Location 56.6
I can’t for the life of me work out how to produce this if it is possible.
Can anyone help?
You can use
ROW_NUMBER()effectively here. By Partioning ont2.outcodeand sorting bydistancewe can find the smallest distance for each outcode (t3.rn = 1).