Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Zip2County 1

Status
Not open for further replies.

dave755

IS-IT--Management
May 3, 2001
69
US
I have two tables:
(1) Addr - a list of addresses, including zip codes. This table currently has ~800k rows, but we want to grow it to have ~6M rows.
(2) ZipToCounty - A cross reference of zip codes to the county that each zip code is in. There are 1124 zip codes in 83 counties.

What I want is a table of how many addresses are in each county.

I have been able to do it with this rather clunky bit of SQL using a cursor and a temporary table, but this strikes me as ham-handed and it is already slow.

Code:
declare @County as varchar(30)
declare @cnt as integer
declare cr cursor for 
  select distinct vcCounty 
    from Lookups.dbo.tblluZipToCounty 
    order by vcCounty
create table #CountyCount 
  (
   vcCounty varchar(30), 
   iCount integer
  )
open cr
fetch next from cr into @County
while @@fetch_status = 0 begin
  select @cnt=count(*) from dmvaddr as a
    left outer join Lookups.dbo.tblluZipToCounty as c
    on c.vcZip = a.zip where zip in 
      (select vcZip from Lookups.dbo.tblluZipToCounty
       where vcCounty = @County)
  insert into #CountyCount 
    (vcCounty, iCount) 
     values 
    (@County, @cnt)
  fetch next from cr into @County
end
close cr
deallocate cr
select vcCounty as 'County', iCount as 'Registrants' 
  from #CountyCount order by vcCounty

Is there a more elegant way to get my answer.

Dave Gee
 
Wow, talk about round the houses! ;-)

Code:
SELECT z.vccounty, COUNT(*) AS registrants
FROM dmvaddr d JOIN Lookups.dbo.tblluZipToCounty z ON d.zip = z.vczip
GROUP BY z.vccounty
ORDER BY z.vccounty

--James
 
Looks OK, though counties without addresses won't be listed because of inner join.
 
Thanks for the guidance. This was exactly what I was hoping to get with this posting.

Dave Gee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top