gpt4 book ai didi

mysql - 如何用sql语句生成结果?

转载 作者:行者123 更新时间:2023-11-29 18:45:04 25 4
gpt4 key购买 nike

原表:

enter image description here

查看结果中的国家/地区列。总之,我想列出每个国家中人口最多的省份,然后列出每个国家中人口第二多的省份。

有人可以帮我解决这个问题吗?

最佳答案

Rextester Demo

您的预期输出有 2 个差异。

  1. c2p1 800位于 c3p2 900 之前我认为这是不正确的。

  2. 结果,第 7 行是 c2p1但应该是c3p1我认为这是一个错字。

我还将生成序列号的逻辑留给了您,您可以轻松地通过谷歌搜索。

select t1.country,t1.province,t1.population
from tbl1 t1
inner join tbl1 t2
on t1.country=t2.country
where t1.population <= t2.population
group by t1.country,t1.province
order by count(*),t1.population desc;

输出

+---------+----------+------------+
| country | province | population |
+---------+----------+------------+
| C1 | C1P3 | 1500 |
| C3 | C3P2 | 900 |
| C2 | C2P1 | 800 |
| C4 | C4P1 | 100 |
| C1 | C1P1 | 1000 |
| C2 | C2P2 | 500 |
| C3 | C3P1 | 100 |
| C1 | C1P2 | 500 |
+---------+----------+------------+

说明:自加入 where状况where t1.population <= t2.populationgroup by t1.country,t1.province将复制Windows功能row_Number() over partition by这在 MySQL 中是不可用的。

限制:假设 ONLY_FULL_GROUP_BY已为您禁用,否则您将需要再加入一个来显示 population因为它不在 group by 中字段。

关于mysql - 如何用sql语句生成结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44711487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com