【问题标题】:Use subquery and possible join to get population percentage使用子查询和可能的连接来获取人口百分比
【发布时间】:2018-07-26 03:09:37
【问题描述】:

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

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

我需要使用值的另一个查询是: SELECT sum(populationcount), age, educationattainment from education_attainment group by age, educationattainment 此处的结果显示了 12 个不同的人口计数值,每个年龄组内获得的每种教育水平都有一个值。

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

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

【问题讨论】:

    标签: mysql join subquery division coefficients


    【解决方案1】:

    您应该改用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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      相关资源
      最近更新 更多