I have a table
Country Population Continent
I am asked to find
For each continent, find the country with largest % of populaiton in every continent.
Sample Output
Country Population_Rate Continent
1 30% A
2 40% B
No window function is allowed.No CTE.
I can find the largest population, but I am not sure how to calculate rate (country_population/continent_population).
SELECT *, FROM t t1
WHERE population > ALL(SELECT * FROM t t2 WHERE t1.continent = t2.continent)
-- find largest population for each continent
The sample data of Popuation_rate = '30%' which looks like a string
It is easier if the sample data looks like 0.3 or even 30
For demo, Imaging the data type is numeric, eg 30 (not 30%)
For each continent, find the country with largest % of populaiton in every continent.
And thanks for your update, your table structure as following:
Country, Population, Continent
SELECT a.Country, a.Population / b.total * 100 AS Population_Rate, a.Continent
FROM tab AS a
JOIN (
SELECT Continent, SUM(Population) AS total, MAX(Population) AS max_pop
FROM tab
GROUP BY Continent
) AS b ON a.Continent = b.continent AND a.Population = b.max_pop
SELECT T.Country, MAX(M.Population_Rate) as Population_Rate, T.Continent
FROM tab T
JOIN
(SELECT tab.Country, tab.Population/tot.Cont_Total*100 as Population_Rate, tab.Continent
FROM tab
JOIN (
SELECT Continent, SUM(Population) as Cont_Total
FROM tab
GROUP BY Continent
) AS tot ON tot.Continent=tab.Continent
) AS M
ON M.Continent=T.Continent AND M.Population_Rate=MAX(M.Population_Rate)
GROUP BY M.Continent;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.