Home > Enterprise >  How can i find the maximum gdp per population in sql?
How can i find the maximum gdp per population in sql?

Time:12-16

I have 2 tables countries and coutry_stats.

Countries table

Country_id name country_code
1 Aruba AW
2 Afghanistan AF

Country_stats table

Country_id year population gdp
1 1986 62644 405463417
1 1987 61833 487602457
1 1988 61079 596423607
1 1989 61032 695304363
1 1990 62149 764887117
1 1991 64622 872138730
2 1960 8996973 537777811
2 1961 9169410 548888895
2 1962 9351441 546666677
2 1963 9543205 751111191
2 1964 9744781 800000044
2 1965 9956320 1006666638

How can i find the maximum gdp / popupation along the years?

i tried

select 
  countries.country_id, 
  name, 
  country_code, 
  year, 
  gdp, 
  population, 
  max(gdp / population) as per_ratio 
from 
  countries JOIN country_stats on 
  countries.country_id = country_stats.country_id
where 
  countries.country_id = 1 group by name order by per_ratio;

but im getting this

Country_id name country_code year gdp population per_ratio
1 Aruba AB 1986 405463417 62644 27084.7037

the per_ratio is the correct maximum of this country but this is not the correct record in the database.

CodePudding user response:

This would likely yield the result you're looking for - it sorts per_ratio DESC and limits that record to one.

SELECT
   countries.country_id, 
   name, 
   country_code, 
   year, 
   gdp, 
   population, 
   gdp / population as per_ratio 
FROM countries 
JOIN country_stats 
   on countries.country_id = country_stats.country_id 
WHERE countries.country_id = 1
ORDER BY per_ratio DESC
LIMIT 1;

Alternatively, you could use a partition to first get the max for the country id in a CTE, and then pull in all records where max_per_ratio = per_ratio

WITH MAX_PER AS(
SELECT
   countries.country_id, 
   name, 
   country_code, 
   year, 
   gdp, 
   population, 
   gdp / population as per_ratio,
   MAX(gdp/population) OVER(PARTITION BY country_id) AS max_per_ratio
FROM countries 
JOIN country_stats 
   on countries.country_id = country_stats.country_id 
WHERE countries.country_id = 1)

SELECT
   country_id, 
   name, 
   country_code, 
   year, 
   gdp, 
   population, 
   per_ratio 
FROM MAX_PER
WHERE max_per_ratio = per_ratio;
  • Related