我有一张桌子
Country Population Continent
我被要求找到
对于每个大陆,找到拥有最大人口百分比的国家 每个大陆。
示例输出
Country Population_Rate Continent
1 30% A
2 40% B
不允许使用窗口功能。没有CTE。
我可以找到最大的人口,但我不知道如何计算费率(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
答案 0 :(得分:0)
Popuation_rate = '30%'的样本数据,看起来像一个字符串
如果样本数据看起来像0.3或甚至30
,则会更容易对于演示,成像数据类型是数字,例如30(不是30%)
对于每个大陆,找到每个大洲拥有最多人口百分比的国家。
感谢您的更新,您的表格结构如下:
国家,人口,大陆
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
答案 1 :(得分:0)
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;