0

I'm given this schema:

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

I've written this query which lists the department codes along with the average ages of employees just fine:

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

However, when I try to do something like this:

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

It returns the wrong Department ID. It just returns 0 for that column but it returns the minimum age of the previous table. However, the Department ID with the lowest age is 4. What am I doing wrong?

4

1 回答 1

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;
于 2013-07-11T13:02:36.927 回答