You can combine joins and subqueries
in a single query. Suppose that you want to find the city nearest
to each city in the USCITYCOORDS table. The query must first select
a city
A
, compute the distance from
a city
A
to every other city, and finally
select the city with the minimum distance from city A. This can be
done by joining the USCITYCOORDS table to itself (self-join) and then
determining the closest distance between cities by using another self-join
in a subquery.
This is the formula
to determine the distance between coordinates:
SQRT(((Latitude2−Latitude1)**2) + ((Longitude2−Longitude1)**2))
Although the results
of this formula are not exactly accurate because of the distortions
caused by the curvature of the earth, they are accurate enough for
this example to determine whether one city is closer than another.
libname sql 'SAS-library';
proc sql outobs=10;
title 'Neighboring Cities';
select a.City format=$10., a.State,
a.Latitude 'Lat', a.Longitude 'Long',
b.City format=$10., b.State,
b.Latitude 'Lat', b.Longitude 'Long',
sqrt(((b.latitude-a.latitude)**2) +
((b.longitude-a.longitude)**2)) as dist format=6.1
from sql.uscitycoords a, sql.uscitycoords b
where a.city ne b.city and
calculated dist =
(select min(sqrt(((d.latitude-c.latitude)**2) +
((d.longitude-c.longitude)**2)))
from sql.uscitycoords c, sql.uscitycoords d
where c.city = a.city and
c.state = a.state and
d.city ne c.city)
order by a.city;
Combining a Join with a Subquery
The outer query joins
the table to itself and determines the distance between the first
city A1 in table A and city B2 (the first city that is not equal to
city A1) in Table B. PROC SQL then runs the subquery. The subquery
does another self-join and calculates the minimum distance between
city A1 and all other cities in the table other than city A1. The
outer query tests to see whether the distance between cities A1 and
B2 is equal to the minimum distance that was calculated by the subquery.
If they are equal, then a row that contains cities A1 and B2 with
their coordinates and distance is written.