我如何仅按字母顺序在SQL查询中保留1个结果?

问题描述 投票:0回答:2

该问题询问的是每个国家的商品总值最高的城市。基本上,有些城市的商品数量相同,但我们只按字母顺序保留第一个。结果仅包含国家/地区名称,商品数量最多的城市及其商品总数。

我的查询结果:

France            Paris        85
Germany           Berlin       100
Germany           Frankfurt    100
Germany           Luxembourg   100
Netherlands       Amsterdam    75
Spain             Barcelona    93

正确的结果应该是:

France            Paris        85
Germany           Berlin       100
Netherlands       Amsterdam    75
Spain             Barcelona    93
sql greatest-n-per-group tie
2个回答
1
投票

将聚合函数min()用于城市,将max()用于no_of_goods。

select country, min(city) as city, max(no_of_goods) as no_of_goods from tableA
group by country

0
投票

您可以使用row_number()

select t.*
from (select t.*, row_number() over (partition by country order by city) as seq,
             max(no_goods) over (partition by country) as max_good
      from table t
     ) t
where seq = 1;
© www.soinside.com 2019 - 2024. All rights reserved.