Here is one way to do it. I didn't spend a whole lot of time on this and I'm sure it can be optimized--it accesses the base table 4 times--but if it's just a one-time thing it shouldn't be too bad.
declare @z table
(
zip5 char(5),
zip4 char(4),
county varchar(50),
city varchar(50)
)
insert @z
select '90001', '0001', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0002', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0003', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0004', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0005', 'LOS ANGELES', 'FONTAINE'
union all select '90001', '0006', 'LOS ANGELES', 'FONTAINE'
union all select '90001', '0007', 'LOS ANGELES', 'FONTAINE'
union all select '90001', '0008', 'LOS ANGELES', 'FONTAINE'
union all select '90001', '0009', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0010', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0011', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0012', 'LOS ANGELES', 'LOS ANGELES'
union all select '90001', '0013', 'LOS ANGELES', 'FONTAINE'
union all select '90001', '0014', 'LOS ANGELES', 'FONTAINE'
union all select '90001', '0015', 'LOS ANGELES', 'FONTAINE'
select
z_min.zip5,
z_min.zip4 as min_zip4,
(
select top(1)
z3.zip4
from @z z3
where
z3.zip5 = z_min.zip5
and z3.zip4 >= z_min.zip4
and z3.county = z_min.county
and z3.city = z_min.city
and not exists
(
select *
from
(
select top(1)
z4.county,
z4.city
from @z z4
where
z4.zip5 = z3.zip5
and z4.zip4 > z3.zip4
order by z4.zip4 asc
) y
where
y.city = z3.city
and y.county = z3.county
)
order by z3.zip4 asc
) as max_zip4,
z_min.county,
z_min.city
from
(
select
z1.zip5,
z1.zip4,
z1.county,
z1.city
from @z z1
where
not exists
(
select *
from
(
select top(1)
county,
city
from @z z2
where
z2.zip5 = z1.zip5
and z2.zip4 < z1.zip4
order by zip4 desc
) x
where
x.county = z1.county
and x.city = z1.city
)
) z_min