title: MySQL query to find the department with the lowest average age of employees
body: <p>I'm given this schema:</p>
  
  <pre><code>Emp(eid: integer,ename: string,age: integer,salary: real)
  Works(eid:integer,did: integer,pct_time: integer)
  Dept(did:integer,budget: real,managerid:integer)
  </code></pre>
  
  <p>I've written this query which lists the department codes along with the average ages of employees just fine:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>However, when I try to do something like this:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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?</p>