title: Min, Max, Group By and DateDiff
body: <p>I'm trying to optimise many MySQL statements into one but have come across a problem.</p>
  
  <p>MySQL query:</p>
  
  <pre><code>  SELECT companyid, COUNT(*) AS total 
      FROM timesheet 
     WHERE userId='1' 
       AND DATEDIFF(MIN(startDate), MAX(endDate)) &lt;= 77 
  GROUP BY companyid 
    HAVING total = 11
  </code></pre>
  
  <p>What I'm trying to do is select all companies where exactly 11 records exist and the first and last records were created within 11 weeks of each other. The error I get is "Invalid use of group function".</p>
  
  <p>This is to do with the <code>MIN(), MAX()</code> and <code>DATEDIFF()</code> part but I can't for the life of me figure it out!</p>