MySQL查询查找员工平均年龄最低的部门

时间:2013-03-14 20:32:38

标签: mysql sql database

我给了这个架构:

Emp(eid: integer,ename: string,age: integer,salary: real)
Works(eid:integer,did: integer,pct_time: integer)
Dept(did:integer,budget: real,managerid:integer)

我写了这个查询,其中列出了部门代码以及员工的平均年龄:

SELECT d.did AS Department, AVG(e.age) AS Average_Age
FROM Emp e, Works w, Dept d
WHERE e.eid=w.eid AND w.did=d.did
GROUP BY d.did

然而,当我尝试做这样的事情时:

SELECT Department, MIN(Average_Age)
FROM 
(
SELECT d.did AS Department, AVG(e.age) AS Average_Age
WHERE e.eid=w.eid AND w.did=d.did
GROUP BY d.did
) MyTable

它返回错误的部门ID。它只返回该列的0,但它返回上一个表的最小年龄。但是,年龄最低的部门ID是4.我做错了什么?

1 个答案:

答案 0 :(得分:0)

请你试试这个:

SELECT department, MIN(avg_age)
FROM
(
    SELECT dept.did AS department, AVG(emp.age) AS avg_age FROM dept
    LEFT JOIN works ON works.did = dept.did
    LEFT JOIN emp ON emp.eid = works.eid
    GROUP BY dept.did
) AS test
ORDER BY 1 LIMIT 1;