Jamie Taylor
Jamie Taylor

Reputation: 3530

Complicated oracle query

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?

Upvotes: 1

Views: 320

Answers (1)

Conrad Frix
Conrad Frix

Reputation: 52645

You can use ROW_NUMBER() effectively here. By Partioning on t2.outcode and sorting by distance we can find the smallest distance for each outcode (t3.rn = 1).

SELECT 
       t1.Name,
       t1.Postcode,
       t2.Lat,         
       t2.Long,    
       t3.Nearest_Loc,
       t3.Distance
From 
      table1 t1 
       INNER join table2 t2 on t2.outcode = t1.post_code
    LEFT JOIN (
               SELECT t3.location_name, 
                     calc_distance(t3.lat, t3.lng, t2.lat,t2.lng) as distance,
                     row_number() over (partition by t2.outcode 
                                        order by calc_distance(t3.lat, t3.lng, t2.lat,t2.lng) 
                                      ) rn,
                    t2.outcode
               FROM table3 t3, table2 t2 
            ) t3
     on t1.Postcode =  t3.PostCode
      and t3.rn = 1

Upvotes: 1

Related Questions