title: mysql reference not supported to group function
body: <p>I have a MySQL procedure that takes in 2 parameters <code>par_DateFrom</code> and <code>par_DateTo</code></p>
  
  <p>I'm getting a nasty error. I'm pretty sure that reusing alias TotalDaysOut to calculate TotalIncome is the culprit. How can I fix this elegantly?</p>
  
  <p><strong>Error 1247:</strong>
  reference <code>TotalDaysOut</code>not supported reference to group function</p>
  
  <pre><code>BEGIN
  SELECT  t.LicencePlate
              ,f.Make
              ,f.Model
              ,f.Year
  
              ,COUNT(t.LicencePlate) AS TotalTrx          
              ,SUM(DATEDIFF(IF(checkedIn &gt;par_DateTo, par_DateTo, checkedIn) ,IF(checkedOut &lt;par_DateFrom, par_DateFrom, checkedOut))) AS TotalDaysOut
              ,SUM(t.Price* (SELECT TotalDaysOut)) AS TotalIncome
  FROM        TRANSACTIONS    t
  INNER JOIN FLEET            f
      ON t.LicencePlate = f.LicencePlate
  WHERE t.CheckedOut &lt; par_DateTo AND t.CheckedIn &gt; par_DateFrom
  GROUP BY t.LicencePlate
              ,f.Make
              ,f.Model
              ,f.Year;
  END
  </code></pre>