合并 3 个表并在 SQL 中查找平均年龄
Combining 3 Tables and Finding Average Age in SQL
我需要合并三个表,并在使用 SQL 合并三个表后求出平均年龄。三个表中年龄列的名称分别为pr16pnk.age、pr16puf.age和pr16yag.age。当表格分开时,我已经成功地找到了结果,但是我在合并结果时遇到了麻烦。下面列出的是我使用的代码。
SELECT AVG(pr16pnk.age) AS MeanAge
FROM pr16pnk
UNION ALL
SELECT AVG(pr16puf.age) AS MeanAge
FROM pr16puf
UNION ALL
SELECT AVG(pr16yag.age) AS MeanAge
FROM pr16yag
您可以使用两个级别的聚合。对于平均值的平均值:
SELECT AVG(MeanAge)
FROM (SELECT AVG(pr16pnk.age) AS MeanAge
FROM pr16pnk
UNION ALL
SELECT AVG(pr16puf.age) AS MeanAge
FROM pr16puf
UNION ALL
SELECT AVG(pr16yag.age) AS MeanAge
FROM pr16yag
) a;
但是,您可能真正想要的是总体平均值,其计算方式为:
SELECT AVG(MeanAge),
SUM(sum_age) / SUM(cnt)
FROM (SELECT AVG(pr16pnk.age) AS MeanAge, SUM(age) as sum_age, COUNT(*) as cnt
FROM pr16pnk
UNION ALL
SELECT AVG(pr16puf.age) AS MeanAge, SUM(age) as sum_age, COUNT(*) as cnt
FROM pr16puf
UNION ALL
SELECT AVG(pr16yag.age) AS MeanAge, SUM(age) as sum_age, COUNT(*) as cnt
FROM pr16yag
) a;
我需要合并三个表,并在使用 SQL 合并三个表后求出平均年龄。三个表中年龄列的名称分别为pr16pnk.age、pr16puf.age和pr16yag.age。当表格分开时,我已经成功地找到了结果,但是我在合并结果时遇到了麻烦。下面列出的是我使用的代码。
SELECT AVG(pr16pnk.age) AS MeanAge
FROM pr16pnk
UNION ALL
SELECT AVG(pr16puf.age) AS MeanAge
FROM pr16puf
UNION ALL
SELECT AVG(pr16yag.age) AS MeanAge
FROM pr16yag
您可以使用两个级别的聚合。对于平均值的平均值:
SELECT AVG(MeanAge)
FROM (SELECT AVG(pr16pnk.age) AS MeanAge
FROM pr16pnk
UNION ALL
SELECT AVG(pr16puf.age) AS MeanAge
FROM pr16puf
UNION ALL
SELECT AVG(pr16yag.age) AS MeanAge
FROM pr16yag
) a;
但是,您可能真正想要的是总体平均值,其计算方式为:
SELECT AVG(MeanAge),
SUM(sum_age) / SUM(cnt)
FROM (SELECT AVG(pr16pnk.age) AS MeanAge, SUM(age) as sum_age, COUNT(*) as cnt
FROM pr16pnk
UNION ALL
SELECT AVG(pr16puf.age) AS MeanAge, SUM(age) as sum_age, COUNT(*) as cnt
FROM pr16puf
UNION ALL
SELECT AVG(pr16yag.age) AS MeanAge, SUM(age) as sum_age, COUNT(*) as cnt
FROM pr16yag
) a;