title: SQL Error: ORDER BY error on aggregating field,
body: <p>I have a query that I keep receiving an error code of:</p>
  
  <blockquote>
    <p>Column "#t_APPS.DaysToDocs" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.</p>
  </blockquote>
  
  <p>with the following query. But I don't understand since the column is being aggregated (averaged) .. Help please. </p>
  
  <pre><code>SELECT TOP 80 PERCENT
      ta2.YoMo                    AS [YoMo]
      ,ta2.ProdCat_NID            AS [ProdCat_NID]
      ,ta2.AffilTXT               AS [AffilTXT]
      ,ISNULL(COUNT(DISTINCT ta2.AppDetID),-99) AS [NumDocsSentTop80]
      ,ISNULL(AVG(ta2.DaysToDocs*1.00),-999)*1.00  AS [eAvgDaysToDocsTop80]
  FROM #t_APPS ta2
  WHERE ta2.Rtype like 'DOCSSENT'
  GROUP BY ta2.YoMo, ta2.ProdCat_NID, ta2.AffilTXT
  ORDER BY ta2.DaysToDocs ASC
  </code></pre>
  
  <p>Maybe I'm going about this the wrong way for what I'm looking for. :/</p>
  
  <p>I'm trying to get the Average of the best/top 80% of the DaysToDocs 
  I thought by doing <em>Select top 80 percent [...] Order by DaysToDocs</em>  would give me the top 80%,  and the AVG(DaysToDocs) would then only average on that subset of records. </p>