-1

该问题要求以每个国家/地区的客户购买商品金额最高的城市为例。基本上,有些城市的商品数量相同,但我们只保留第一个按字母顺序排列。结果仅包含国家名称、商品数量最多的城市及其商品总和。

表架构:

Country table:
country_name
city_name

Goods table:
city_name
user_id
number_of_goods

我的查询结果:

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
4

3 回答 3

1

您可以使用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;
于 2020-01-30T08:30:10.177 回答
1

min()对 city 和max()no_of_goods使用聚合函数。

select t1.country, t1.no_of_goods, min(t2.city) as city 
from
(select country,  max(no_of_goods) as no_of_goods from tableA
group by country) t1
left join tableA t2 on t2.no_of_goods = t1.no_of_goods and t1.country = t2.country
group by t1.country, t1.no_of_goods

dbfiddle

于 2020-01-30T08:30:26.407 回答
0

基本上,有些城市的商品数量相同,但我们只保留第一个按字母顺序排列。

根据您的样本数据,一个国家的所有城市似乎都有相同的number_of_goods. 如果是这样,您可以只使用聚合:

select c.country, min(c.city_name), max(number_of_goods)
from countries c join
     goods g
     on c.city_name = g.city_name
group by c.country;
于 2020-01-30T12:31:32.087 回答