【问题标题】:How to select biggest zip code for each country [closed]如何为每个国家/地区选择最大的邮政编码[关闭]
【发布时间】:2021-03-30 19:04:55
【问题描述】:

在每个国家/地区,哪个城市的邮政编码最高? 仅选择国家名称和城市名称

这是一个图形模式,可能会对您有所帮助:

这是我到目前为止所做的:

SELECT CountryName, CityName
from City ci
join County co on co.CountryID = ci.CountryID
group by CountryName, CityName, ci.ZipCode
having ZipCode = MAX(ZipCode)

如果有人能帮我解决这个问题,我将不胜感激。

【问题讨论】:

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

标签: sql sql-server database greatest-n-per-group lateral-join


【解决方案1】:

你也可以试试这个。在外部查询中使用排名函数并对其进行拟合

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

【讨论】:

    【解决方案2】:

    一个选项使用横向连接:

    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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多