无法创建子查询

时间:2018-06-11 00:22:58

标签: mysql

我有一个主要问题:

SELECT
  SUM(population_count),
  age
FROM educational_attainment
GROUP BY age;

这给了我年龄组的总人口。

第二个查询是:

SELECT
  EducationalAttainment,
  age,
  SUM(population_count) 
FROM educational_attainment
GROUP BY EducationalAttainment, age;

这给了我年龄组的子群体及其教育程度。

因此,如果年龄组从18岁到65岁的总人口是第一次查询的200万,我从第二次查询得到34000年龄组。

如何将两个查询组合起来计算2,000,000个中的34,000个分数。谢谢。

1 个答案:

答案 0 :(得分:2)

供参考:

SELECT
  by_attainment.EducationalAttainment AS education_attainment,
  by_attainment.age AS age,
  (by_attainment.population_sum/total.population_sum*100) AS percentage,
  total.population_sum AS total_population_sum,
  by_attainment.population_sum AS by_attainment_population_sum
FROM (
  SELECT
    SUM(population_count) AS population_sum,
    age
  FROM educational_attainment
  GROUP BY age
) AS total,
(
  SELECT
    EducationalAttainment,
    age,
    SUM(population_count) AS population_sum
  FROM educational_attainment
  GROUP BY EducationalAttainment, age
) AS by_attainment
WHERE total.age = by_attainment.age;

使用test data on db-fiddle.com的结果:

+-------------------------------------+-----------+------------+----------------------+------------------------------+
|        education_attainment         |    age    | percentage | total_population_sum | by_attainment_population_sum |
+-------------------------------------+-----------+------------+----------------------+------------------------------+
| Bachelor's degree or higher         | 00 to 17  |     0.1499 |              9787619 |                        14673 |
| Bachelor's degree or higher         | 18 to 64  |    30.3232 |            151806895 |                     46032757 |
| Bachelor's degree or higher         | 65 to 80+ |    29.7863 |             28772453 |                      8570246 |
| High school or equivalent           | 00 to 17  |     1.1737 |              9787619 |                       114881 |
| High school or equivalent           | 18 to 64  |    23.4361 |            151806895 |                     35577621 |
| High school or equivalent           | 65 to 80+ |    25.1992 |             28772453 |                      7250424 |
| No high school diploma              | 00 to 17  |    97.7411 |              9787619 |                      9566523 |
| No high school diploma              | 18 to 64  |     16.701 |            151806895 |                     25353234 |
| No high school diploma              | 65 to 80+ |    19.9813 |             28772453 |                      5749114 |
| Some college, less than 4-yr degree | 00 to 17  |     0.9353 |              9787619 |                        91542 |
| Some college, less than 4-yr degree | 18 to 64  |    29.5397 |            151806895 |                     44843283 |
| Some college, less than 4-yr degree | 65 to 80+ |    25.0332 |             28772453 |                      7202669 |
+-------------------------------------+-----------+------------+----------------------+------------------------------+