我有一个主要查询:
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 的分数。谢谢。
最佳答案
供引用:
<小时/>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 |
+-------------------------------------+-----------+------------+----------------------+------------------------------+
关于mysql - 创建子查询时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50789177/