使用子查询和可能的连接来获取人口百分比

Use subquery and possible join to get population percentage

我正在学习 MySQL,我想进行两个查询,将每个查询中的 sum(populationcount) 值除以得出单独列中列出的百分比(作为小数值)。目标是使用我将在下面列出的第一个查询作为子查询来显示每个年龄组获得的每种教育的百分比。

我需要用作子查询的查询是这样的: SELECT age,SUM(populationcount) FROM educational_attainment GROUP BY age; 人口计数结果只有三个不同的值,它们将作为新查询中的除数。

我需要使用值的另一个查询是: SELECT sum(populationcount), age, educationalattainment from educational_attainment group by age, educationalattainment 此处的结果显示了 12 个不同的 populationcount 值,每个值对应每个年龄组内获得的每个教育水平。

我的查询有点接近,看起来像这样: SELECT A.EducationalAttainment, A.age, A.populationcount/B.age FROM educational_attainment A JOIN (SELECT age, sum(populationcount ) age_populationcount FROM educational_attainment 按年龄分组) B ON A.age=B.age; 不幸的是,它为我提供了每个年龄组的太多结果,并且计算值大于 0 而不是小于 0 的小数值。

我希望我解释得足够好。如果有人对我做错了什么有任何见解,我将非常感谢您的意见!谢谢!

您应该使用 LEFT JOIN 代替,如下图所示:

SELECT 
    A.age, B.educationalattainment, 
    (IFNULL(B.pop_count, 0)/A.pop_count)*100 percentage_pop
FROM
(SELECT 
    age, SUM(populationcount) pop_count 
 FROM educational_attainment 
 GROUP BY age) A
LEFT JOIN 
(SELECT 
    sum(populationcount) pop_count, age, educationalattainment 
 FROM educational_attainment 
 GROUP BY age, educationalattainment) B
ON A.age=B.age;