Sql 如何为每个国家选择最大的邮政编码

Sql 如何为每个国家选择最大的邮政编码,sql,sql-server,database,greatest-n-per-group,lateral-join,Sql,Sql Server,Database,Greatest N Per Group,Lateral Join,在每个国家,哪个城市的邮政编码最高? 仅选择国家名称和城市名称 以下是一个图形模式,可以帮助您: 这就是我到目前为止所做的: 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 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
您还可以使用
行编号()

如果正在运行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

您使用的是SQL Server还是MS Access?请移除其中一个标签。请同时显示(以文本格式而不是图像)一些示例数据和预期结果。SQL Server(Transact-SQL)我将尝试从GROUP BY子句中删除ci.zipcode,因为您正在尝试查找最大值。如果将其包含在GROUP BY中,则将获得所有zipcode。
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