如何获得国家明智的人口最多的城市

时间:2021-04-30 15:00:51

标签: sql

我目前正在搜索执行以下操作的 SQL 查询:

我有一张表格,列出了全球所有城市及其国家和人口。

例如表“城市”(某些列)

<头>
姓名 国家 人口
柏林 德国 3640000
纽约 美国 8419000
汉堡 德国 1841000
洛杉矶 美国 3967000

我知道需要找到每个国家/地区人口最多的城市。

例如想要的结果

<头>
姓名 人口 国家
柏林 3640000 德国
纽约 8419000 美国

问题在于这个查询:

SELECT name, MAX(population) FROM city GROUP BY country

不会返回合适的城市名称。我知道为什么会发生这种情况,但不确定如何以其他方式解决它。

感谢任何帮助!谢谢!

4 个答案:

答案 0 :(得分:2)

ANSI SQL 解决方案几乎对任何 rdbms 使用子查询:

 create table city (name varchar(50),country    varchar(50), population int);
 insert into city values('Berlin'   ,'Germany', 3640000);
 insert into city values('New York' ,'USA', 8419000);
 insert into city values('Hamburg'  ,'Germany', 1841000);
 insert into city values('Los Angeles'  ,'USA', 3967000);

查询:

 select name, population, country from city c
 where population=(select max(population ) from city a where  a.country=c.country)

输出:

<头>
名称 人口 国家
柏林 3640000 德国
纽约 8419000 美国

dbhere

答案 1 :(得分:1)

您需要标记您的 dbms ,但这适用于包括 mariadb 在内的大多数数据库,使用窗口函数将避免两次命中城市表:

select * from 
  (
   select * , row_number() over (partition by country order by population desc) rn
   from city
  ) t
where rn = 1

答案 2 :(得分:0)

您可以使用“不存在”

SELECT * from country a
where not exists
(
select 1 from country b 
where a.country = b.country
and b.population > a.population
)

答案 3 :(得分:0)

<div class="form-group">
<label>Seats (uppercase letters only)<span class="text-danger">*</span></label>
<input type="text" name="seats" class="form-control" pattern="^[A-k0-9{0,3}]+(, [A-k0-9]{0,3}+)*$" title="That seat doesn't exist. Please try again." required >
</div>