如何从 sql 中的 2 个表中按组聚合和计算平均值?
Posted
技术标签:
【中文标题】如何从 sql 中的 2 个表中按组聚合和计算平均值?【英文标题】:How to aggregate and count avg value by groups from 2 tables in sql? 【发布时间】:2020-01-07 09:40:32 【问题描述】:我有 2 张桌子,部门和员工。我需要获取部门名称和平均年龄。
create table Dep(name_dep char, id_dep int);
insert into Dep values("econ", 1);
insert into Dep values("credit", 2);
insert into Dep values("energy", 3);
insert into Dep values("retail", 4);
insert into Dep values("manufactury", 5);
create table Emp(id_emp int, id_dep int, age int, person_name char, salary int );
insert into Emp values(1, 1, 23, 'john', 200);
insert into Emp values(3, 2, 3, 'dalbai', 100);
insert into Emp values(6, 3, 53, 'borat', 300);
insert into Emp values(7, 1, 63, 'erjan', 1600);
insert into Emp values(9, 2, 73, 'sergey', 1000);
insert into Emp values(8, 5, 83, 'lucy', 20);
insert into Emp values(90, 4, 93, 'mike', 1200);
如何选择部门名称和该部门员工的平均年龄?
SELECT name_dep, average_age
FROM Emp e
INNER JOIN
(
SELECT name_dep, AVG(age) AS average_age
FROM Dep d
GROUP BY id_dep
) d
ON e.id_dep = d.id_dep
【问题讨论】:
指定预期的结果,如上表数据。 您不能从Dep
表中选择AVG(age)
,因为那里不存在age
列。您的子查询需要从Emp
表中进行选择。
@ERJAN 你有什么理由不接受最早的答案吗?
【参考方案1】:
你可以试试下面 -
DEMO
select name_dep,avg(age)
from emp a inner join dep b on a.id_dep=b.id_dep
group by a.id_dep,name_dep
【讨论】:
【参考方案2】:加入表格,group by id_dep, name_dep
,然后得到平均年龄:
select
d.name_dep, avg(age) average_age
from Dep d inner join Emp e
on e.id_dep = d.id_dep
group by d.id_dep, d.name_dep
请参阅demo。 结果:
| name_dep | average_age |
| ----------- | ----------- |
| econ | 43 |
| credit | 38 |
| energy | 53 |
| retail | 93 |
| manufactury | 83 |
【讨论】:
【参考方案3】:你可以做类似的事情
SELECT
d.name_dep, AVG(age) as avg_age
FROM
Emp e, Dep d
WHERE
e.id_dep = d.id_dep
GROUP BY
d.name_dep
【讨论】:
【参考方案4】:SELECT d.name_dep,AVG(e.age)
FROM Dep d JOIN Emp e ON d.id_dep = e.id_dep
GROUP BY d.name_dep;
【讨论】:
以上是关于如何从 sql 中的 2 个表中按组聚合和计算平均值?的主要内容,如果未能解决你的问题,请参考以下文章