title: SQL Query aggregate may not appear in WHERE clause
body: <p>I have this SQL statement and SQL Server is giving me the following error: </p>
  
  <blockquote>
    <p>An aggregate may not appear in the WHERE clause unless it is in a
    subquery contained in a HAVING clause or a select list.</p>
  </blockquote>
  
  <pre><code>SELECT 
    SUM(M1.InvoiceTotal)-SUM(M1.AmountApplied) as PastDueAmount
    , M1.BillingID
    , M2.Name
    , M2.DelinquentDaysThreshold
    , M2.DelinquentAmountThreshold
    , DATEDIFF(d, MIN(BillingDate),GETDATE()) as DaysLate
  FROM Invoices M1 
  LEFT JOIN ClientAccounts M2 ON M1.BillingID = M2.ID
  WHERE 
    InvoiceTotal &lt;&gt; AmountApplied
    AND M2.DelinquentDaysThreshold &gt; DATEDIFF(d, MIN(BillingDate),GETDATE())
    OR (SUM(M1.InvoiceTotal)-SUM(M1.AmountApplied)) &gt; M2.DelinquentAmountThreshold
  GROUP BY 
    M1.BillingID
    , M2.Name
    , M2.DelinquentDaysThreshold
    , M2.DelinquentAmountThreshold
  </code></pre>
  
  <p>In the where clause, I only want to pull records where the oldest unpaid Billing Invoice Date is greater than the DelinquentDaysThreshhold (in days), OR the PastDueAmount (a calculated value) is greater than the DelinquentAmountThreshold.<br>
  For some reason SQL Server does not like aggregated amounts.</p>