无限制地选择最高值

时间:2015-11-06 14:29:52

标签: sql postgresql greatest-n-per-group

我有以下关系模式:

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

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

2 个答案:

答案 0 :(得分:2)

使用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;

答案 1 :(得分:1)

只需添加另一个子选择,返回最大语言数:

Dim nameValuePairs = HttpUtility.ParseQueryString(New Uri("https://api.worldoftanks.eu/wot/globalmap/clanbattles/?application_id=b72a008042b0afa92aa44bd9fc20f5d9&clan_id=500061064").Query)