gpt4 book ai didi

sql - 无限制地选择最高值

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

我有以下关系模式:

Country(code: Str, name: Str, capital: Str, area: int)
code (this is the usual country code, e.g. CDN for Canada, F for France, I for Italy)
name (the country name) capital (the capital city, e.g. Rome for Italy)
area (The mass land the country occupies in square Km)

Economy (country: Str, GDP: int, inflation: int, military: int, poverty: int)
country is FK to the Country table
GDP (gross domestic product)
inflation (annual inflation rate)
military (military spending as percentage of the GDP)
poverty rate (percentage of population below the poverty line)

Language (country: Str, language: Str, percentage: int)
country is FK to the Country table
language is a spoken language name
percentage (percentage of population speaking the language)

我需要编写一个查询,以找到使用最多语言的国家/地区的贫困率

我写了这个查询

SELECT poverty
FROM(
SELECT COUNT(language) as langnum, country
FROM "Language"
GROUP BY country) AS conto
JOIN "Economy" AS E
ON E.country=conto.country
ORDER BY conto.langnum DESC
LIMIT 1

显然只有当我有一个国家拥有最大语言数量时它才有效,如果有多个国家拥有最大语言数量我该怎么办?

最佳答案

使用rank()dense_rank():

SELECT poverty
FROM (SELECT COUNT(language) as langnum, country,
RANK() OVER (ORDER BY COUNT(language) DESC) as ranking
FROM "Language"
GROUP BY country
) conto JOIN "Economy" AS E
ON E.country=conto.country
WHERE conto.ranking = 1
ORDER BY conto.langnum DESC;

关于sql - 无限制地选择最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569070/

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