如何 select 每个国家/地区的最大邮政编码
How to select biggest zip code for each country
In each country, which city has the highest ZIP code?
Select only the Country name, and the city name
这里有一个图解,可能对你有帮助:
这是我目前所做的:
SELECT CountryName, CityName
from City ci
join County co on co.CountryID = ci.CountryID
group by CountryName, CityName, ci.ZipCode
having ZipCode = MAX(ZipCode)
如果有人能解决这个问题,我将不胜感激。
一个选项使用横向连接:
select co.countryname, ci.cityname, ci.zipcode
from country co
cross apply (
select top (1) with ties ci.*
from city ci
where ci.countryid = co.countryid
order by ci.zipcode desc
) ci
您也可以使用 row_number()
:
select co.countryname, ci.cityname, ci.zipcode
from country co
inner join (
select ci.*, rank() over(partition by countryid order by zipcode desc) rn
from city ci
) ci on ci.countryid = co.countryid
如果您是运行 MS Access,您可以使用相关子查询:
select co.countryname, ci.cityname, ci.zipcode
from country co as co
inner join city as ci on ci.countryid = co.countryid
where ci.zipcode = (
select max(c1.zipcode)
from city as ci1
where ci1.countryid = ci.country
)
你也可以试试这个。使用排名函数并在外部查询中对其进行过滤
select * from
(select c1.countryname as countryname, c2.cityname as cityname,
max_city_zip = rank() Over (partition by c1.countryname order by c2.cityname desc)
from country c1
inner join city c2
on c1.countryID = c2.countryID
group by c1.countryname, c2.cityname)Y where max_city_zip = 1
In each country, which city has the highest ZIP code? Select only the Country name, and the city name
这里有一个图解,可能对你有帮助:
这是我目前所做的:
SELECT CountryName, CityName
from City ci
join County co on co.CountryID = ci.CountryID
group by CountryName, CityName, ci.ZipCode
having ZipCode = MAX(ZipCode)
如果有人能解决这个问题,我将不胜感激。
一个选项使用横向连接:
select co.countryname, ci.cityname, ci.zipcode
from country co
cross apply (
select top (1) with ties ci.*
from city ci
where ci.countryid = co.countryid
order by ci.zipcode desc
) ci
您也可以使用 row_number()
:
select co.countryname, ci.cityname, ci.zipcode
from country co
inner join (
select ci.*, rank() over(partition by countryid order by zipcode desc) rn
from city ci
) ci on ci.countryid = co.countryid
如果您是运行 MS Access,您可以使用相关子查询:
select co.countryname, ci.cityname, ci.zipcode
from country co as co
inner join city as ci on ci.countryid = co.countryid
where ci.zipcode = (
select max(c1.zipcode)
from city as ci1
where ci1.countryid = ci.country
)
你也可以试试这个。使用排名函数并在外部查询中对其进行过滤
select * from
(select c1.countryname as countryname, c2.cityname as cityname,
max_city_zip = rank() Over (partition by c1.countryname order by c2.cityname desc)
from country c1
inner join city c2
on c1.countryID = c2.countryID
group by c1.countryname, c2.cityname)Y where max_city_zip = 1