I have two tables of zipcodes containing drivetime data. The first (called "DTM") contains 4 columns. The first two columns are From and To zipcodes, followed by drivetime and driving distance between them. This table contains every combination of zipcodes twice, with From and To zips reversed. it looks something like this:
FROM_ZIP TO_Zip Drivetime(min) Distance(mtr)
1011 1011 0 0
1011 1012 3 650
1011 1013 4 850
1011 1014 4 900
1012 1011 3 650
1012 1012 0 0
1012 1013 2 500
...
This table contains roughly 16.5 million records.
The second table (called "STOREZIPS") contains a list of zipcodes belonging to stores.
My goal here is to match every zipcode in the country to the zipcode of the store that is closest by, and show the drivetime and driving distance. So what i'm trying to do is extract from the first table the rows in which the TO_Zip
matches one of the zipcodes in the second table, and have the lowest Drivetime(min)
.
There are however also instances where two Zip's have the same Drivetime(min)
to another Zip. If this occurs the row with the lowest Distance(mtr)
should be selected.
I've been trying to solve this for a while now, but just can't seem to get it in such a way that only the From_Zip
that is closest by gets selected.
Any help or suggestion is appreciated.
I think that you will need to use CTE in that case. You can read more here: https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx
If I understood you well I think that sample sql may look like this:
with cte as
(
select min(c.Drivetime) as minimum, c.zipT,
c.Distance, rank() over (partition by c.TO_Zip order by c.Distance) as place
from DTM c
inner join STOREZIPS s on c.TO_Zip = s.TO_Zip
where c.Drivetime > 0
group by c.TO_Zip, c.Distance
) select * from cte where place = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.